list - F# 记录和列表排序

标签 list sorting f# records

我是 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/

相关文章:

静态成员约束函数的性能

c# - 从列表中删除重复项,但保留一个并进行编辑

python - 如何根据条件python查找字符串中字母的位置

java - 图像图标列表

javascript - 需要根据某种逻辑对Javascript数组进行排序

Java 在忽略撇号的同时对列表进行排序

string - 如何在 F# 中使用 String.iter

powershell - 在生产环境中使用 F# 脚本替换 powershell?

Python 导出一些列表并将所有列表放入 for 循环中

php - php array_multisort 是如何工作的?