3

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?

1 Answer 1

7
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
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that solved it. I'm glad it was just something simple like that.
As a rule of thumb, always parenthesize expression which are an argument to a prefix function, if they are more than just a variable name.
Note this is why x : f y works, because the function application f y binds more tightly than :, so it's as if you had parenthesized x : (f y)
Actually the error message is this way because : binds more tightly than -, so it's parsed as (l : (myTake n)) - (1 ls). This is why it complains that the second argument of : is a function - myTake is only partially applied.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.