0

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.

smilingbuddha
  • 14,334
  • 33
  • 112
  • 189

2 Answers2

9

You will need to put parentheses around your error message in line 5.

Currently your implementation is equal to this one:

(error "The array contains fewer than ") ++ show k ++  "elements"

While you most likely wanted it to do this:

error ("The array contains fewer than " ++ show k ++  "elements")

You can also use the ($) syntax like so:

error $ "The array contains fewer than " ++ show k ++  "elements"
Community
  • 1
  • 1
Tim Bodeit
  • 9,673
  • 3
  • 27
  • 57
8

According to Haskell Report, f x ++ g y parses as (f x) ++ (g y). In your case,

error "The array contains fewer than " ++ (show k) ++  "elements"

parses as

(error "The array contains fewer than ") ++ (show k) ++  "elements"
dfeuer
  • 48,079
  • 5
  • 63
  • 167
Yuras
  • 13,856
  • 1
  • 45
  • 58