我有以下的功能就像一个索引操作:Haskell中的Just是什么?为什么没有它,这个函数不能工作?
let {
index :: [a]->Int->Maybe a
index [] i = error "Empty list"
index l i = if i <= ((length l) - 1) && i >= 0 then
Just(l !! i)
else
error "Index out of bounds"
}
现在,我开始写这不使用Just
(和我还是不明白什么是谷歌搜索后):
let {
index :: [a]->Int->Maybe a
index [] i = error "Empty list"
index l i = if i <= ((length l) - 1) && i >= 0 then
(l !! i)
else
error "Index out of bounds"
}
对我而言,上述功能非常有意义。因为这里我有一个函数,它接受'通用类型'a
和Int
这是索引并返回Maybe
值a
的值或抛出运行时异常。但是,我不明白的地方GHCI告诉我这个位:
<interactive>:1:120:
Couldn't match type `a' with `Maybe a'
`a' is a rigid type variable bound by
the type signature for index :: [a] -> Int -> Maybe a
at <interactive>:1:34
Expected type: [Maybe a]
Actual type: [a]
In the first argument of `(!!)', namely `l'
In the expression: (l !! i)
现在,为什么GHCI感到困惑与l
类型,为什么它期待Maybe a
类型的列表?最后,Just
如何解决问题?
代码大师,现在我的代码在你编辑后看起来很舒服:) – badmaash 2012-07-26 21:03:56
你真的喜欢用你最初发布的单行代码写你的定义吗? – gspr 2012-07-26 21:04:34
其实,我绝对不会写这样的单行,因为我来自C++/VB.NET背景。由于Haskell为我提供了选择编写 - 编译 - 执行还是只写执行的选项,我的懒惰更喜欢第二种选择。另外,我刚开始学习它,所以只有'玩具程序'会这样写。也许我不知道我是否可以在GHCi的多行中分割我的代码,是吗? – badmaash 2012-07-26 21:12:06