[英]Choosing whether to use Discriminated Unions or Record Types for a small AST in F#
[英]Higher verbosity when using Record types in F# in comparison with Discriminated Unions
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.