I am just a few days into Haskell and learning it from Learn You a Haskell for a great good. While trying out one of the 99 Haskell problems, I ran into the following error while loading my function into ghci.
The problem asks to write a function elementAt k x
which takes a number k, a list x and extracts the kth
element of the list x.
Here is my function
elementAt :: Int -> [a] -> a
elementAt k x
| k < 0 = error "You have passed a negative index"
| null x = error "Cannot extract from an empty list"
| (length x) < k = error "The array contains fewer than " ++ (show k) ++ "elements"
elementAt 0 (x:_) = x
elementAt k (_:xs) = elementAt (k-1) xs
On loading this function into ghci I get the error
Couldn't match expected type `a' with actual type `[Char]'
`a' is a rigid type variable bound by
the type signature for elementAt :: Int -> [a] -> a at fun.hs:77:14
Relevant bindings include
x :: [a] (bound at fun.hs:78:13)
elementAt :: Int -> [a] -> a (bound at fun.hs:78:1)
In the expression:
error "The array contains fewer than " ++ (show k) ++ "elements"
In an equation for `elementAt':
elementAt k x
| k < 0 = error "You have passed a negative index"
| null x = error "Cannot extract from an empty list"
| (length x) < k
= error "The array contains fewer than " ++ (show k) ++ "elements"
The trouble seems to lie with the way I have used the show
function, but I
don't see why. On removing the show
call the function seems to compile and
work perfectly.