与Discriminated Unions相比,在F#中使用Record类型时更高的详细程度

时间:2011-08-24 22:23:34

标签: .net f# functional-programming record discriminated-union

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#中使用记录类型时无法避免这种冗长。我是对的吗?

1 个答案:

答案 0 :(得分:6)

记录非常类似于只有一个案例的歧视联盟。在某些情况下,我也更喜欢工会,因为它更容易使用。但是,记录有两个主要优点:

  • 他们给字段命名,这部分导致冗长,但使代码更加不言自明 如果您有少量字段,则可以使用元组或单例联合。

  • 它们允许您使用{ 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