Haskell function definition not working as expected

I am new to functional programming and Haskell. Trying to find out. Not sure what is wrong with the following definition:

Function definition in test.h

drop5 [a]  = drop 5 [a] 

      

While trying to use this function I am getting program error

$:load test.h
$drop5 [2,3,4,5,6,7,8]
Program error: pattern match failure: drop5 [2,3,4,5,6,7,8]
$:t drop5
drop5 :: [a] -> [a]

      

When I change the definition so that it is executed; which means it takes a list and strips off the first 5 elements of the list

drop5 ns = drop 5 ns

      

And in this case, when the print type I see:

$:t drop5
drop5 :: [a] -> [a]

      

I'm not sure why the first definition is different from the second? And what does the error "Program error: pattern match failed" mean?

+3


source to share


3 answers


In the first definition [a]

, it is a pattern that matches only one element, and that element becomes known as a

on the right side of the rule.

This way you define the function as only receiving single lists.



Also, removing 5 elements from a list that has only one clearly results in empty lists (as does removing any positive number of elements).

+5


source


Defining your function:

drop5 [a] = drop 5 [a]

      

Indicates that the sentence only "works" for lists with exactly one item. Indeed, in a function definition, it is [a]

not a parameter type , it is a template . The template [a]

means that we are working with a list with only one element.



If you compile -Wall

, you get:

<interactive>:1:1: warning: [-Wincomplete-patterns]
    Pattern match(es) are non-exhaustive
    In an equation for โ€˜drop5โ€™:
        Patterns not matched:
            []
            (_:_:_)

      

Thus, the compiler / interpreter generates a warning that two patterns are not considered: one for an empty list and one for a list with two or more elements.

+4


source


[a]

tells Haskell that there is only one element in the list, and ns

tells Haskell that it can be anything (even boolean if you want) until the function ends, and it identifies the output and input type. You can also tell Haskell explicitly what the input and output type is by adding this above this line:

drop5 :: [Integer] -> [Integer]

      

Which can be found by doing :t drop5

the GHCI.

Also, on a side note, this code can be reduced. By changing it to:

drop5 = drop 5

      

This may not make sense to you right now, but as you learn more, you should learn that all Haskell functions take one argument.

+2


source







All Articles