【发布时间】:2015-09-08 03:10:59
【问题描述】:
我刚接触 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 调用该函数似乎编译和
完美运行。
【问题讨论】:
标签: haskell