gpt4 book ai didi

f# - 构造复杂对象图的计算表达式

转载 作者:行者123 更新时间:2023-12-04 19:54:38 24 4
gpt4 key购买 nike

给定以下类型:

type Trip = {
From: string
To: string
}

type Passenger = {
Name: string
LastName: string
Trips: Trip list
}

我正在使用以下构建器:

type PassengerBuilder() = 
member this.Yield(_) = Passenger.Empty

[<CustomOperation("lastName")>]
member __.LastName(r: Passenger, lastName: string) =
{ r with LastName = lastName }

[<CustomOperation("name")>]
member __.Name(r: Passenger, name: string) =
{ r with Name = name }

type TripBuilder() =
member __.Yield(_) = Trip.Empty

[<CustomOperation("from")>]
member __.From(t: Trip, f: string) =
{ t with From = f }

// ... and so on

创建 Passenger 类型的记录,如下所示:

let passenger = PassengerBuilder()
let trip = TripBuilder()

let p = passenger {
name "john"
lastName "doe"
}

let t = trip {
from "Buenos Aires"
to "Madrid"
}

我要如何组合 PassengerBuilderTripBuilder 才能实现这种用法?

let p = passenger {
name "John"
lastName "Doe"
trip from "Buenos Aires" to "Madrid"
trip from "Madrid" to "Paris"
}

返回一个 Passenger 记录,如:

{
LastName = "Doe"
Name = "John"
Trips = [
{ From = "Buenos Aires"; To = "Madrid" }
{ From = "Madrid"; To = "Paris" }
]
}

最佳答案

您有什么理由要使用计算表达式生成器吗?根据您的示例,您看起来不像是在编写任何类似计算的东西。如果你只是想要一个很好的 DSL 来创建旅行,那么你可以很容易地定义一些让你写的东西:

let p = 
passenger [
name "John"
lastName "Doe"
trip from "Buenos Aires" towards "Madrid"
trip from "Madrid" towards "Paris"
]

这几乎正是您所要求的,除了它使用 [ .. ] 而不是 { .. } (因为它创建了一个转换列表) .我还将 to 重命名为 towards 因为 to 是一个关键字,你不能重新定义它。

此代码很容易编写和遵循:

let passenger ops = 
ops |> List.fold (fun ps op -> op ps)
{ Name = ""; LastName = ""; Trips = [] }

let trip op1 arg1 op2 arg2 ps =
let trip =
[op1 arg1; op2 arg2] |> List.fold (fun tr op -> op tr)
{ From = ""; To = "" }
{ ps with Trips = trip :: ps.Trips }

let name n ps = { ps with Name = n }
let lastName n ps = { ps with LastName = n }
let from n tp = { tp with From = n }
let towards n tp = { tp with To = n }

也就是说,我仍然会考虑使用普通的 F# 记录语法——它并没有比这更难看。上述版本的一个缺点是您可以创建具有空名称和姓氏的乘客,这是 F# 阻止您做的一件事!

关于f# - 构造复杂对象图的计算表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49117164/

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