使用 F# 的代数数据类型来解决代数问题

Using algebraic data types for F# to solve algebra problems

f# 中的代数数据类型如何工作?我想看一个基本的示例程序来解释它,但似乎找不到。

例如,可能是计算二次公式或求解形状面积的代码。

algebraic data types 中的形容词 algebraic 不是指用于解决代数问题的类型,例如

x + y = 3  or 5 * y = 10

形容词 algebraic 是指类型 constructed/declared 使用 algebraic 乘法运算符 (*) 和加法运算符 (+) 的方式。特别是代数类型可以是 product types (*),它们是元组,例如

type Variable = string * int

sum types,它们使用或字符(|)而不是加号(+),它们是可区分的联合,例如

type Term =
    | Var of Variable
    | Const of Constant
    | App of Constant * Term list

一旦理解了这一点并改变了他们的想法,algebraic data types 上的维基百科文章就应该有意义了,这将解释为什么您没有找到您要找的东西,例如解释如何使用代数数据类型解决代数问题的文章。

本质上,新类型是从 primitive data types such as int, char, string, etc. and the algebraic operators of product and summation but more importantly, algebraic data types are based on type theory and being a formal system 构建而来的,它带来了正式系统的所有好处。

另外值得注意的是声明元组类型的运算符和用于创建元组值的运算符的区别,例如

type Variable = string * int    type
("x",0)                         value

注意类型的 * 运算符和值的 , 运算符。

还有

type Term =                           type
  | Var of Variable
  | Const of Constant
  | App of Constant * Term list  

Var("x",0)                            value
Const("1")                            value
App("add",[Const("1"),Var("x",0)])    value

请注意,每个 possible option 在与值一起使用时必须有一个 case identifier

随着您对 ADT 的了解越来越多,您将 运行 进入 generalized algebraic data type but sadly F# does not have them but have been requested

Mark Seemann 提供了 link 到 Power of mathematics - Reasoning about functional types by Tomas Petricek. Tomas then has a dead link fairly readable introduction but here it is or something similar: What the Heck are Algebraic Data Types? ( for Programmers ) 或我更喜欢 Chris Taylor 使用 Haskell 的系列,但这些想法确实转化为 F#:

The Algebra of Algebraic Data Types, Part 1
The Algebra of Algebraic Data Types, Part 2
The Algebra of Algebraic Data Types, Part 3