gpt4 book ai didi

functional-programming - 函数式编程 : How to model relationships?

转载 作者:行者123 更新时间:2023-12-04 10:34:52 25 4
gpt4 key购买 nike

我想知道如何在函数式编程中建模关系。

我们以员工为例:
员工可以与 0..n 位同事建立友谊。
友谊总是相互的:如果 A 是 B 的 friend ,那么 B 就是 A 的 friend 。

我该如何建模?我有 3 个想法(如下所列)。他们每个人都有缺点。

第一次尝试:

type Employee =
{ name : string
friendships : Employee list
}

// My list is mutable because I want to be able to update employees.
// I suppose the same problems would occur with e. g. Elmish.
let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
Friendships are copies. Changes to an employee would have to be propagated manually.
*)

第二次尝试:
type EmployeeId = int

type Employee =
{ id : EmployeeId
name : string
friendships : EmployeeId list
}

let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
Friendships are not modeled as mutual.
When the friendship of an employee changes,
the friend's friendships don't change accordingly.
*)

第三次尝试:
type EmployeeId = int

type Friendships = list<EmployeeId * EmployeeId>

type Employee =
{ id : EmployeeId
name : string
}

let mutable employees : Employee list = [ (* ... *) ]

(* Downsides:
After deleting an employee from the list,
employeeFriendships contain invalid "references"
to the deleted Employee.
*)

这可以做得更好吗?谢谢你。

最佳答案

使用 let rec/and可能是最直接的方式。您需要通过更改 friendships 来引入懒惰到 IEnumerable .

type Employee =
{
name : string
friendships : seq<Employee>
}

let rec peter = {name="Peter"; friendships=seq {yield paul; yield mary}}
and paul = {name="Paul"; friendships=seq {yield peter; yield mary}}
and mary = {name="Mary"; friendships=seq {yield peter; yield paul}}

但是,编译器给出以下警告:

This and other recursive references to the object(s) being defined will be checked for initialization-soundness at runtime through the use of a delayed reference. This is because you are defining one or more recursive objects, rather than recursive functions. This warning may be suppressed by using '#nowarn "40"' or '--nowarn:40'.



...这指向了一个可以说更好的解决方案:

type Employee =
{
name : string
friendships : unit -> Employee list
}

let rec peter = {name="Peter"; friendships=fun () -> [paul; mary]}
and paul = {name="Paul"; friendships=fun () -> [peter; mary]}
and mary = {name="Mary"; friendships=fun () -> [peter; paul]}

关于functional-programming - 函数式编程 : How to model relationships?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60232682/

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