gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 19:48:22 24 4
gpt4 key购买 nike

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

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

最佳答案

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

x + y = 3  or 5 * y = 10

形容词 algebraic 是指使用乘法 (*) 和加法 (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 建立起来的如intcharstring等以及productsummation<的代数运算符 但更重要的是,代数数据类型基于 type theory并成为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

请注意,每个可能的选项在与值一起使用时都必须有一个case identifier

随着您了解有关 ADT 的更多信息,您将遇到 generalized algebraic data type但遗憾的是 F# 没有它们,但一直是 requested .

Mark Seemann 提供了指向 Power of mathematics - Reasoning about functional types 的链接托马斯·佩特里切克 (Tomas Petricek)。 Tomas 然后有一个死链接 相当可读的介绍 但这里是或类似的东西:What the Heck are Algebraic Data Types? ( for Programmers )或者我更喜欢使用 Haskell 的 Chris Taylor 系列,但这些想法确实转化为 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

关于f# - 使用 F# 的代数数据类型来解决代数问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37388418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com