F# 记录和列表排序

F# records and list sorting

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

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

您可以在执行 List.iter:

之前通过 List.sortBy 传送列表
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)

如您所见,它需要一个函数来获取用于排序的值。传递 (fun s -> s.age) 将使列表按年龄排序。

您可以使用会员权限:

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)