F#从元组列表中提取元组

Kha*_*775 2 f#

我有一个列表clients,其中包含一个string * int * string * int * string list.我做了一个函数,我给了a string,an int和a string list.给定一些规则,我从列表中提取正确的元组.

三个例子clients:

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

//Response must be client(s) with different sex, age diff <= 10 and least one common interest
let request (sex:string) (yob:int) (interests:string list) =
    Set.fold (fun x (nm,ph,sx,yb,toi) -> if sex<>sx && 
                                            yb-yob < 10
                                            then (nm,ph,sx,yb,toi) else x) ("",0,"",0,[]) (Set.ofList file1)

request "Male" 1976 ["Paper"; "Llamas"; "Space"] //Expected ("Jenna", 33658912, "Female", 1970, ["Robe Swinging"; "Llamas"; "Music"])
Run Code Online (Sandbox Code Playgroud)

所以,我想你可以称之为约会局.在上面的例子中,我要求所有客户,这些客户与我的性别不同,年龄差异不大于10岁.我现在没有使用interests,因为我还在努力,但是应该比较给定的兴趣和a的内容client,看看是否至少有一个相似性.

但我目前的问题是它会在第一个兼容的客户端停止并返回,但是如果还有更多呢?如何让它继续并建立一组客户?

我试图做一些事情Set,因此Set.ofList,但是我不知道我Set现在使用a得到任何好处.

Car*_*Dev 7

当使用n> 3或非唯一类型的n元组(此处:五元组)时,我总是感到困惑.记录更容易理解:

type Sex = Male | Female
type Client = { name: string; id: int; sex: Sex; YearOfBirth: int; interests: Set<string> }
Run Code Online (Sandbox Code Playgroud)

构造值更加冗长:

let client1 = { name = "Jon"; id = 37514986; sex = Male; YearOfBirth = 1980; interests = ["Cars"; "Boats"; "Airplanes"] |> Set.ofList }
let client2 = { name = "Jonna"; id = 31852654; sex = Female; YearOfBirth = 1990; interests = ["Makeup"; "Sewing"; "Netflix"] |> Set.ofList }
let client3 = { name = "Jenna"; id = 33658912; sex = Female; YearOfBirth = 1970; interests = ["Robe Swinging"; "Llamas"; "Music"] |> Set.ofList }
let file1   = [client1; client2; client3]
Run Code Online (Sandbox Code Playgroud)

如果您确实需要在代码中列出许多值,请创建一个帮助函数(或构造函数)将元组映射到记录.过滤列表时,您可以只匹配所需的值(请注意,name未使用):

let request sex yob interests =
    file1
    |> List.filter (fun { sex = s; YearOfBirth = y; interests = i } ->
        sex <> s && abs(yob-y)<= 10 && i |> Set.intersect interests |> (not << Set.isEmpty))

request Male 1976 (["Paper"; "Llamas"; "Space"] |> Set.ofList)
Run Code Online (Sandbox Code Playgroud)

val it : Client list = [{name = "Jenna"; id = 33658912; sex = Female; YearOfBirth = 1970; interests = set ["Llamas"; "Music"; "Robe Swinging"];}]