elm - 从 Elm 中的记录列表中返回单个记录

标签 elm

当满足条件时,我试图从记录列表中返回单个记录。
现在,当条件为假时,我正在返回一个包含空字段的记录。

这个可以吗?
有没有更好的办法?

xs =
    [ { name = "Mike", id = 1 }
    , { name = "Paul", id = 2 }
    , { name = "Susan", id = 3 }
    ]


getNth id xs =
    let
        x =
            List.filter (\i -> i.id == id) xs
    in
        case List.head x of
            Nothing ->
                { name = "", id = 0 }

            Just item ->
                item

最佳答案

核心中没有列表搜索功能List包,但社区在 List-Extra 中有一个.有了这个函数,上面的程序就可以写成:

import List.Extra exposing (find)

getNth n xs =
  xs 
  |> find (.id >> (==) n)
  |> Maybe.withDefault { id = n, name = "" }

在 Elm 中处理“可能没有值”的规范方法是返回 Maybe value——这样,getNth的用户可以选择在找不到他要找的值时应该做什么。所以我宁愿省略最后一行,到达非常整洁的地方:
getNth n = find (.id >> (==) n)

关于elm - 从 Elm 中的记录列表中返回单个记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37627593/

相关文章:

榆树 : Compile ELM page to JS

Elm 架构和任务

random - 在 Elm 中生成带有多个参数的消息的命令

elm - 函数式编程 : understand parser combinator

Elm 主函数类型注解

elm - 记录列表中的最大值

Elm:属性 "onerror"改为添加 "data-onerror"属性

dictionary - 如何 Dict.get 不区分大小写的键?

elm - 键盘按键信号丢失

elm - 将 bool 值转换为字符串