当满足条件时,我试图从记录列表中返回单个记录。现在,当条件为假时,我正在返回一条包含空字段的记录。
这个可以吗?有没有更好的办法?
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
Run Code Online (Sandbox Code Playgroud)
核心List包中没有列表搜索功能,但社区在List-Extra 中有一个。有了这个函数,上面的程序就可以写成:
import List.Extra exposing (find)
getNth n xs =
xs
|> find (.id >> (==) n)
|> Maybe.withDefault { id = n, name = "" }
Run Code Online (Sandbox Code Playgroud)
在 Elm 中处理“可能没有值”的规范方法是返回一个Maybe值——这样,getNth当无法找到他正在寻找的值时,用户可以选择应该做什么。所以我宁愿省略最后一行,到达非常整洁的地方:
getNth n = find (.id >> (==) n)
Run Code Online (Sandbox Code Playgroud)