2017-10-21 125 views
2

的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 

任何提示?

回答

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")