gpt4 book ai didi

list - F# 记录和列表排序

转载 作者:行者123 更新时间:2023-11-30 23:52:36 25 4
gpt4 key购买 nike

我是 F# 的新手,正在研究记录和存储/排序它们的方法。我现在拥有的是这个,它工作得相当好......我认为。现在看到这是一种功能性的第一语言,我想尝试对我制作的这个记录列表进行选择。有没有办法访问记录中的元素,以便我可以按年龄排序?还是我以错误的方式思考这个问题

module RecordTypes = 
type Student =
{
Name : string
mutable age : int
mutable major : string
}

let studentOne = { Name = "bob" ; age = 20 ; major = "spanish" }
let studentTwo= { Name = "sally" ; age = 18 ; major = "english" }
let studentThree = { Name = "frank" ; age = 22 ; major = "history" }
let studentFour = { Name = "lisa" ; age = 19 ; major = "math" }
let studentFive = { Name = "john" ; age = 17 ; major = "philosophy" }
// studentFive.age <- studentFive.age + 2
let studentList = [studentOne; studentTwo; studentThree ;studentFour; studentFive]
studentList |> List.iter (fun s-> printf "Name: %s, Age: %d, Major: %s\n" s.Name s.age s.major)

let rec findStudent s = 
match s with
| [] -> None
| x :: xs -> if studentList.Name then return true else findStudent xs

最佳答案

您可以使用成员(member)权限:

studentList
|> List.sortBy (fun s -> s.age)
|> List.iter (fun s -> printf "Name: %s, Age: %d, Major: %s\n" s.Name s.age s.major)

或模式匹配(首选 IMO):

studentList
|> List.sortBy (fun { age=a } -> a)
|> List.iter (fun { Name=n; age=a; major=m } -> printf "Name: %s, Age: %d, Major: %s\n" n a m)

关于list - F# 记录和列表排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33990928/

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