为什么Haskell`show`函数在这里给我带来麻烦?

时间:2015-06-22 15:22:49

标签: haskell

我只是进入Haskell的几天,并从Learn You a Haskell中学到很多东西。在尝试99个Haskell问题之一时,我在将函数加载到ghci时遇到了以下错误。

问题要求写一个函数elementAt k x,它取一个数字k,一个列表x并提取列表x的kth元素。

这是我的功能

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 

在将此函数加载到ghci中时,我收到错误

   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"

问题似乎在于我使用show功能的方式,但我 不明白为什么。在删除show调用时,函数似乎编译并且 完美地工作。

2 个答案:

答案 0 :(得分:9)

您需要在第5行的错误消息周围添加括号。

目前您的实施与此相同:

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

虽然你很可能希望它这样做:

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

您还可以使用($)语法,如下所示:

error $ "The array contains fewer than " ++ show k ++  "elements"

答案 1 :(得分:8)

根据Haskell Reportf x ++ g y解析为(f x) ++ (g y)。在你的情况下,

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

解析为

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