在 F# 中,最接近 Haskell GADT 和类型类的是什么? [英] What's the closest thing to Haskell GADTs and typeclasses in F#?

查看:18
本文介绍了在 F# 中,最接近 Haskell GADT 和类型类的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

F# 是一个带有 OOP 的机器学习.与 Haskell 广义代数数据类型和类型类最接近的是什么?

F# is an ML with OOP. What's the closest it comes to Haskell generalized algebraic data types and typeclasses?

推荐答案

答案取决于您要解决的问题.F# 没有类型类和 GADT,因此没有直接映射.但是,F# 有多种机制可用于解决通常在 Haskell 中使用 GADT 和类型类解决的问题:

The answer depends on what problem are you trying to solve. F# does not have typeclasses and GADTs, so there is no direct mapping. However, F# has various mechanisms that you would use to solve problems that you typically solve in Haskell using GADTs and typeclasses:

  • 如果您想表示对象结构并能够添加具有不同行为的新具体实现,那么您通常可以使用标准的 OO 和接口.

  • If you want to represent object structures and be able to add new concrete implementations with different behaviour, then you can often use standard OO and interfaces.

如果你想写泛型的数字代码,可以使用静态成员约束(这里有一个例子),这可能是技术上最接近类型类的机制.

If you want to write generic numeric code, you can use static member constraints (here is an example), which is probably technically the closest mechanism to type classes.

如果您想编写更高级的通用代码(如通用打印机或解析器),那么您通常可以使用 强大的 F# 运行时反射 功能.

If you want to write more advanced generic code (like universal printer or parser) then you can often use the powerful F# runtime reflection capabilities.

如果您需要通过一组函数(执行代码所需的各种子操作)来参数化代码,那么您可以传递接口的实现,如@pad 所示.

If you need to parameterize code by a set of functions (that perform various sub-operations required by the code) then you can pass around an implementation of an interface as @pad shows.

还有一种方法可以在 F# 中模拟 Haskell 类型类,但是这通常不是惯用的 F# 解决方案,因为 F# 编程风格在许多方面不同于 Haskell 风格.一个相当标准的用法是定义重载运算符(请参阅这个 SO 答案).

There is also a way to emulate Haskell type classes in F#, but this is usually not an idiomatic F# solution, because the F# programming style differs from the Haskell style in a number of ways. One fairly standard use of this is defining overloaded operators though (see this SO answer).

在元级别,询问其他语言中特征 X 的等价物通常会导致混乱的讨论,因为 X 可能用于解决一种语言中的问题 A、B、C 而另一种语言可能会提供不同的功能来解决相同的问题(或者某些问题可能根本不存在).

这篇关于在 F# 中,最接近 Haskell GADT 和类型类的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆