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 lo开发者_运维知识库ad 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?
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
精彩评论