【问题标题】:Position of element in ListList 中元素的位置
【发布时间】: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 cMaybe 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 试过了,更新了帖子。

标签: list elm


【解决方案1】:

首先,将其分解为更简单的indexOf 函数可能有助于避免处理您正在使用的特定元组模型。这使它更清洁,更可重复使用。

我们将indexOf 定义为:

indexOf : a -> List a -> Maybe Int
indexOf el list =
  let
    indexOf' list' index =
      case list' of
        [] ->
          Nothing
        (x::xs) ->
          if x == el then
            Just index
          else
            indexOf' xs (index + 1)
  in
    indexOf' list 0

这里没有什么特别的,只是模式匹配和递归调用。子函数indexOf' 用于跟踪当前索引。

现在我们有了一个通用的indexOf 函数,它可以用于任何可比较的类型,而不仅仅是整数。

接下来,我们需要挤入您的List (Id, ItemModel) 类型列表。这是我们可以在map 函数中使用fst 的地方,创建Ids 的列表。

posInList : Id -> List (Id, ItemModel) -> Int
posInList id list =
  case indexOf id (List.map fst list) of
    Nothing ->
      -1
    Just index ->
       index

在未找到某些东西的情况下,您的原始实现返回 -1,但我认为返回 Maybe Int 会更惯用。这样可以清楚地表明您对使用该库的其他人的意图。

【讨论】:

    【解决方案2】:

    【讨论】:

    • 没错,但我的列表由元组组成,所以我需要.fst 将该元组的 id 与给定的 id 进行比较。但是List.head 的结果给出了Maybe a,我想知道如何摆脱Maybe 并且只有列表。
    猜你喜欢
    • 2014-11-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-22
    • 1970-01-01
    • 1970-01-01
    • 2012-05-27
    • 2011-05-19
    相关资源
    最近更新 更多