Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell Recursion and Type Error

I'm teaching myself Haskell and the best way to learn any programming language is to use it. My current "exercise" is an implementation of take. The pseudo-code is:

take(0, list) = [] --empty list
take(n, list) = const(head(list), take(n-1, tail(list))

What I've worked out in Haskell is:

myTake :: (Num a) => a -> [b] -> [b]
myTake 0 l = []
myTake n (l:ls) = l :  myTake n-1 ls

This doesn't compile when I load the file in GHCi. This is the error message I get:

Couldn't match expected type `[b]'
       against inferred type `[b1] -> [b1]'
In the second argument of `(:)', namely `myTake n - 1 ls'
In the expression: l : myTake n - 1 ls
In the definition of `myTake':
    myTake n (l : ls) = l : myTake n - 1 ls

My current Haskell resource is "Learn You a Haskell for Great Good!" and I've read the section on types several times trying to figure this out. Google has been unusually unhelpful too. I think that I don't entirely understand typing yet. Can anyone explain what's going wrong?

like image 346
T Suds Avatar asked May 23 '26 18:05

T Suds


1 Answers

myTake n - 1 ls

is parsed like

(myTake n) - (1 ls)

because function application binds higher than any infix operator. Parenthesize it:

myTake (n - 1) ls
like image 116
Josh Lee Avatar answered May 25 '26 06:05

Josh Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!