1
votes

I am writing code in Haskell that acts like take, except it takes elements from the end of a list.

snatch :: (Num a, Ord a) => a -> [b] -> [b]
snatch n _
     | n <= 0 = []
snatch _ [] = []
snatch n x = reverse (take n (reverse x))

The problem is with this line,

snatch n x = reverse (take n (reverse x))

It basically states that for take n, n has to be an Int. However, a is a Num type. If I change the definition of the function to this,

snatch :: Int -> [b] -> [b]

Then it works fine. I've tried reading the docs and searching the internet. But I can't find out why. Int is apparently a class of Num. So shouldn't this work? Why doesn't it work?

1
Beware of terminology: Num is a class, but Int is a type, and not a class. We say that Int is an instance of Num. - duplode
Num seems the wrong constraint here, Integral looks better. - chi

1 Answers

6
votes

take, as the name suggests, takes n elements. Going by your logic, if Num was the only criteria, then your function should be able to take, say, 5.4343 elements from the list. Only, that doesn't make sense.

Therefore, in this case, even if Int is an instance of Num, the properties required are those specific to Int.