let Method = { Name:string } //oversimplification
let method_parser =
spaces >>. many1Satisfy isLetter .>> spaces
|>> (fun name -> { Name=name })
如果我选择使用方法判别联合,事情会更简洁:
let method_parser =
spaces >>. many1Satisfy isLetter .>> spaces
|>> Method
我相信在 F# 中使用记录类型时没有办法避免这种冗长的情况。我说得对吗?
最佳答案
记录与只有一个案例的可区分联合非常相似。在某些情况下,我也更喜欢联合,因为它更容易使用。然而,记录有两个主要优点:
它们为字段命名,这在一定程度上导致了冗长,但使代码更加不言自明
如果字段数量较少,可以使用元组或单例联合。它们允许您使用
{ info with Name = "Tomas"}
语法来克隆记录
如果您不需要这个,您可以使用标准 F# 类(更具 .NET 风格)
如果您想获得记录的好处,但仍然使用简单的语法来创建记录,那么您可以定义一个静态成员来构造记录:
type Info =
{ Name : string
Count : int }
static member Create(name:string, count:int) =
{ Name = name; Count = count }
然后你可以写:
// Simple example using the above type:
let res = ("hello", 5) |> Info.Create
// I expect this would work for your type like this:
let method_parser =
spaces >>. many1Satisfy isLetter .>> spaces
|>> Method.Create
关于.net - 与可区分联合相比,在 F# 中使用记录类型时更加详细,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7183040/