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

时间:2017-11-12 22:51:30

标签: f#

我有clients的列表,其中包含string * int * string * int * string list。我创建了一个功能,我提供stringintstring 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"])

所以,我想你可以称之为约会局。在上面的例子中,我要求所有与我没有共同性别并且年龄差异不大于10的客户。我现在没有使用interests,因为我&#39 ; m仍然在努力,但它应该比较给定的兴趣和client的内容,看看是否至少有一个相似性。

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

我正在尝试使用Set做一些事情,因此Set.ofList,但我不知道如何使用Set获得任何好处,因为它现在就是。

1 个答案:

答案 0 :(得分:7)

当使用n元组(此处:五元组)时,我总是感到困惑,n&gt; 3或非独特类型。记录更容易理解:

261067842 / 86400

构造值更加冗长:

type Sex = Male | Female
type Client = { name: string; id: int; sex: Sex; YearOfBirth: int; interests: Set<string> }

如果确实需要在代码中列出许多值,请创建一个帮助函数(或构造函数)将元组映射到记录。 过滤列表后,您可以只匹配所需的值(请注意,未使用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] ):

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)