.net - 与可区分联合相比,在 F# 中使用记录类型时更加详细

标签 .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# 中使用记录类型时没有办法避免这种冗长的情况。我说得对吗?

最佳答案

记录与只有一个案例的可区分联合非常相似。在某些情况下,我也更喜欢联合,因为它更容易使用。然而,记录有两个主要优点:

  • 它们为字段命名,这在一定程度上导致了冗长,但使代码更加不言自明
    如果字段数量较少,可以使用元组或单例联合。

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

相关文章:

c# - 如何删除所有 Click 事件处理程序?

.net - 二进制序列化命名空间更改

c# - 为什么 System.Exception.ToString 不为内部异常调用虚拟 ToString?

f# - 嵌套循环和函数式编程

Json 解析 F#

functional-programming - 基本算法的函数式编程

c# - 以编程方式反汇编 CIL

list - F# 记录和列表排序

compiler-construction - 为解释器评估 AST 节点时的循环函数调用

algorithm - 在函数范式中实现 Karger 的最小割算法