Reputation: 103
I am new to functional programming and Haskell. Trying to learn it. Not sure what is wrong with the following definition:
Function definition in test.h
drop5 [a] = drop 5 [a]
Trying to use this function I get 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 to following it works; meaning it takes a list and drops first 5 elements of the list
drop5 ns = drop 5 ns
And in this case when print type I see:
$:t drop5
drop5 :: [a] -> [a]
I am not sure why is the first definition different than second? And what does the error "Program error: pattern match failure means"?
Upvotes: 3
Views: 481
Reputation: 456
[a]
is telling Haskell that there is only one element in a list, while ns
tells Haskell that it could be anything (even a boolean if you want) until you finish the function and it identifies the output and input type. You could also explicitly tell Haskell what the input and output type is by adding this above that line:
drop5 :: [Integer] -> [Integer]
Which could be found by doing :t drop5
in 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.
Upvotes: 2
Reputation: 476493
Your function definition:
drop5 [a] = drop 5 [a]
Specifies that the clause only "fires" for lists with exactly one element. Indeed in a function definition [a]
is not the type of the parameter, it is a pattern. The pattern [a]
means that we are working with a list with exactly one element.
If you compile with -Wall
you will get:
<interactive>:1:1: warning: [-Wincomplete-patterns]
Pattern match(es) are non-exhaustive
In an equation for ‘drop5’:
Patterns not matched:
[]
(_:_:_)
The compiler/interpreter thus produces a warning that two patterns are not covered: one for an empty list, and one for a list with two or more elements.
Upvotes: 4
Reputation: 11940
In the first definition, [a]
is a pattern that only matches a list of exactly one element, and that element becomes known as a
in the right part of the rule.
Thus, you define the function as only accepting singleton lists.
Moreover, dropping 5 elements from a list that only has one obviously results in an empty list (as does dropping of any positive number of elements).
Upvotes: 5