【发布时间】:2012-07-26 20:48:09
【问题描述】:
我有以下函数,其作用类似于索引运算符:
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如何解决问题?
【问题讨论】:
-
Code-Guru,现在我的代码在您编辑后看起来很舒服 :)
-
您真的更喜欢将您的定义写在您最初发布的单行上吗?
-
实际上,我永远不会写这样的单行代码,因为我来自 C++/VB.NET 背景。由于 Haskell 为我提供了写-编译-执行或只写-执行的选项,我的懒惰更喜欢第二种选择。另外,我刚刚开始学习它,所以只有“玩具程序”才会这样写。也许我不知道我是否可以在 GHCi 中将我的代码拆分为多行,是吗?
-
LYAH 为初学者提供了关于 Maybe、Just 和 Nothing 的不错解释。 learnyouahaskell.com/…