2017-10-21 92 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")