我有以下代码 -
let items = [
(20,"cat");
(13,"can");
(19,"letter");
(55,"dog");
(87,"kettle");
(122,"weight");
]
有人可以给我举个例子,给出编号为 13 的项目名称吗?我尝试的一切都返回错误,在网上查找了一些示例,但没有一个!
注意 - 以前的解决方案不起作用。执行此操作的最简单方法是什么?
let getName people id =
people
|> Seq.filter (fun person -> fst person = id)
|> Seq.head
|> snd
// or: |> Seq.filter (fst >> (=) id)
let getId people name =
people
|> Seq.filter (fun person -> snd person = name)
|> Seq.head
|> fst
let getNames people =
people
|> List.map snd
您可以按如下方式调用它们:
printfn "%d" (getId people "LIAM")
printfn "%s" (getName people 44567)
printfn "%A" (getNames people)