【发布时间】:2015-12-13 15:47:57
【问题描述】:
我正在尝试在给定 ID 的列表中获取元素的索引。这就是我所拥有的:
type alias Id = Int
posInList : Id -> List (Id, ItemModel) -> Int
posInList id list =
if List.isEmpty list then
-1
else
if (List.head list).fst == id then
0
else
if posInList id (List.tail list) == -1 then
-1
else
posInList id (List.tail list) + 1
我从 here 找到的方案代码中得到了这个答案(以 7 票回答)。
编译代码时出现两个错误:
我该如何解决这个问题?还是有更简单的解决方案?
更新:用 Maybe 试了一下
posInList : Id -> Maybe List (Id, ItemModel) -> Int
posInList id list =
case list of
Nothing -> -1
Just a ->
case (List.head a) of
Just b ->
if b.fst == id then
0
else
case (List.tail a) of
Nothing -> -1
Just c -> (posInList id (Just c)) + 1
Nothing -> -1
我想我已经接近了,但我无法解决此错误:
Just c 是Maybe List 类型,但它与Maybe 有什么冲突?
我想到了类型注释,所以我添加了这样的括号:
posInList : Id -> Maybe (List (Id, ItemModel)) -> Int
然后我得到:
现在我一无所知,从未见过这样的错误。
【问题讨论】:
-
(List.head list).fst我认为 List.head 返回一个元素而不是列表。尝试不致电.fst -
您的可能类型声明在哪里?即函数签名中没有对它的引用......为什么要在列表中添加 1?
-
Maybe是 ELM 中的核心类型:package.elm-lang.org/packages/elm-lang/core/3.0.0/Maybe -
当然,但它仍然有签名。你有使用haskell的经验吗?
-
是的,一点点,我用 Maybe 试过了,更新了帖子。