开发者

Haskell Recursion and Type Error

开发者 https://www.devze.com 2023-02-13 15:45 出处:网络
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:

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
0

精彩评论

暂无评论...
验证码 换一张
取 消