gpt4 book ai didi

F#在从记录列表派生的 map 上应用 Map.filter

转载 作者:行者123 更新时间:2023-12-01 09:14:55 25 4
gpt4 key购买 nike

我有这些记录:

type Name        = string
type PhoneNumber = int
type Sex = Male | Female
type YearOfBirth = int
type Interests = string list
type Client = {name: Name; phone: PhoneNumber; sex: Sex; birth: YearOfBirth; interests: Interests}

let client1 = {name = "Jon"; phone = 37613498; sex = Male; birth = 1980; interests = ["Cars"; "Boats"; "Airplanes"]}
let client2 = {name = "Jonna"; phone = 31852654; sex = Female; birth = 1970; interests = ["Makeup"; "Sewing"; "Bananas"]}

我将其放入列表中:

let file1 = [client1;client2]

然后我尝试使用 Map 创建一个函数,它应该能够过滤 file1 并且只返回客户端,该客户端的生日与功能。

例子:

requestMap 1980

在这种情况下会返回 map [("Jon", (37613498, Male, 1980, ["Cars"; "Boats"; "Airplanes"]))]

我偶然发现了一个函数,但我现在有点卡住了。

let requestMap yob =
Map.ofList [for f in file1 do yield f.name,(f.phone,f.sex,f.birth,f.interests)] |>
Map.filter (fun key value -> )

我无法弄清楚如何在当前 map 的 value 中获得 birth?因为就像现在一样,它隐藏在 value 中,目前是一个 PhoneNumber * Sex * YearOfBirth * Interests 元组。

有什么提示吗?

最佳答案

要访问元组的元素,您可以使用模式匹配:

Map.filter (fun key (phone, sex, birth, interests) -> birth = yob)

或者,如果您对出生年份以外的任何内容都不感兴趣,则可以使用下划线忽略所有其他字段:

Map.filter (fun _ (_, _, birth, _) -> birth = yob)

也就是说,我建议先过滤,然后再创建 map ,这样会更便宜:

let requestMap yob = 
file1
|> List.filter (fun x -> x.birth = yob)
|> List.map (fun f -> f.name,(f.phone,f.sex,f.birth,f.interests))
|> Map.ofList

当我们谈到这个主题时:为什么首先需要创建那个巨大的元组?你不能让原始记录成为 map 中的值吗?像这样:

let requestMap yob = 
file1
|> List.filter (fun x -> x.birth = yob)
|> List.map (fun f -> f.name, f)
|> Map.ofList

关于F#在从记录列表派生的 map 上应用 Map.filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47310135/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com