Reputation: 1307
I am new to Haskell (started learning it today) and I am implementing my own take
method as follows:
grab :: (Num a, Ord a) => a -> [b] -> [b]
grab n _
| n <= 0 = []
grab _ [] = []
grab n (x:xs) = x : grab (n - 1) xs
It compiles and works just fine. But how come when I change the definition from
grab :: (Num a, Ord a) => a -> [b] -> [b]
to
grab :: (Num a, Ord a) => a -> [b] -> [c]
It does not compile and throws an error? It is my understanding that the variables in the function definition don't really mean anything, and that they can be replaced by virtually anything.
So then why is it wrong to say the return value is [c]
? Why do I have to use [b]
? I do not understand.
Upvotes: 1
Views: 70
Reputation: 21757
[a] -> [b] -> [b]
means that your input parameters are a value of type a
and a list
of type b
and your output is a list
of type b
. Your logic is implementing take
, so it stands to reason that the list
you return must be of the same type as the list
you take as input.
If you do [a]->[b]->[c]
you are saying that you want to return a list
of a different data type. This would be valid if you did something to transform to that data type, but that isn't the case here.
Therefore, in your desired implementation the output has to be of type [b]
and not [c]
.
Upvotes: 3