F#遍历不同类型的列表

时间:2017-10-21 16:44:39

标签: list f#

我有五种不同的类型:

type Name        = string
type PhoneNumber = int
type Sex         = string
type YearOfBirth = int
type Interests   = string list
type Client      = Name * PhoneNumber * Sex * YearOfBirth * Interests

代表客户。然后,让我说我有三个这样的客户:

let client1 = "Jon", 37514986, "Male", 1980, ["Cars"; "Sexdolls"; "Airplanes"]
let client2 = "Jonna", 31852654, "Female", 1990, ["Makeup"; "Sewing"; "Netflix"]
let client3 = "Jenna", 33658912, "Female", 1970, ["Robe Swinging"; "Llamas"; "Music"]
let clients = [client1; client2; client3]

我如何通过clients搜索特定元素?说,我有一个方法,我想得到与我性别相同的客户的名字?我已经写了下面这个函数,至少可以确定输入性是否相同但是并没有明显减少它。

let rec sexCheck sex cs = 
match cs with
| [] -> []
| c::cs -> if sex = c then sex else sexCheck sex cs

sexCheck "Male" clients

任何提示?

1 个答案:

答案 0 :(得分:4)

您可以将结果累积到另一个参数中,如下所示:

let sexCheck sex cs = 
    let rec loop acc (sex:string) cs = 
        match cs with
        | [] -> acc
        | ((_, _, s, _, _) as c)::cs -> loop (if sex = s then c::acc else acc) sex cs
    loop [] sex cs

像往常一样,我想通过使用F#中提供的函数来提醒您最简单的方法:

clients |> List.filter (fun (_, _, c, _, _) -> c = "Male")