F#中的绝对初学者 - 需要帮助

时间:2013-02-21 10:15:53

标签: string f#

我有以下代码 -

let items = [
    (20,"cat");
    (13,"can");
    (19,"letter");
    (55,"dog");
    (87,"kettle");
    (122,"weight");
]

有人可以给我看一个例子,它会给出13号项目的名称吗? 我尝试的所有内容都会返回错误,在线查看一些示例,但没有一个在那里!

注意 - 以前的解决方案不起作用。执行此操作的最简单方法是什么?

1 个答案:

答案 0 :(得分:1)

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)