当满足条件时,我试图从记录列表中返回单个记录。
现在,当条件为假时,我正在返回一个包含空字段的记录。
这个可以吗?
有没有更好的办法?
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/