3
votes

I am learning Haskell using Learn You a Haskell. On page 54 is an implementation of take like so:

take' :: (Num i, Ord i) => i -> [a] -> [a]
take' n _
    | n <= 0 = []
take' _ []   = []
take' n (x:xs) = x : take' (n-1) xs

I understand all the code apart from the first line.

The :: part I understand as meaning this is a type definition?

(Num i, Ord i) is a tuple. The first element of the tuple has to be numeric, fair enough. the second param has to be able to be ordered. The parameter is the same - both are i. This means that the types have to be the same?

Why is it not (Num i, Ord j)? Isn't the 2nd tuple element referring to the list? Which could be of any type?

What does => signify?

i -> [a] -> [a] means first parameter is numeric? 2nd param is any type list, 3rd param is any type list. So this is saying first param numeric, 2nd param a list of any type and it returns a list of any type. Well that is understandable I suppose.

2

2 Answers

12
votes

The stuff before the => are constraints. (Num i, Ord i) isn't really a tuple in the usual sense. It specifies a requirement that type class instances exist for whatever specific type i you call the function with.

So what this type signature is actually saying is that the type of take' is i -> [a] -> [a], but with the additional restriction that i must have Num and Ord instances, which amounts to requiring that you can do some basic arithmetic (Num being short for "numeric" I suppose) and compare which value is larger (Ord meaning values of that type have an ordering defined, i.e. you can sort them or such).

In this particular case, the comparison n <= 0 is what uses Ord, while the subtraction and numeric literals use Num.

This is covered in chapter 3 of LYAH, and these specific type classes (among others) are mentioned in the Typeclasses 101 section.

2
votes

(Num i, Ord i) is not meant to be a tuple. Read the type signature as: take' is a function of the type i -> [a] -> [a] where i has to be a type of the typeclasses Num and Ord.

You might want to read the chapter "Typeclasses 101" again.