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

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

问题描述

F#是具有OOP的ML.与Haskell广义代数数据类型和类型类最接近的是什么?

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

推荐答案

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

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.

如果要编写更高级的通用代码(例如通用打印机或解析器),则通常可以使用

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天全站免登陆