类型的替代?

时间:2010-09-08 02:34:42

标签: haskell f# functional-programming typeclass

haskell程序员。使用F#。 F#中没有类型类。我需要类型类时要用什么?

1 个答案:

答案 0 :(得分:20)

按照建议的人查看this

我认为简短的回答是通过操作词典(正如Haskell所说的那样;实例的证人)。

或者更改设计,这样就不需要类型类。 (这总是让人感到痛苦,因为类型类别是有史以来最好的东西而且很难让它们落后,但是在Haskell和类型类出现之前,人们仍然设法在没有类型类别的情况下以某种方式编程了40年,所以那些人做了同样的事情。)

您还可以通过inline静态成员约束获得一些方法,但这很快就会变得难看。

这是一个操作词典示例:

// type class
type MathOps<'t> = { add : 't -> 't -> 't; mul: 't -> 't -> 't }  //'

// instance
let mathInt : MathOps<int> = { add = (+); mul = (*) }

// instance
let mathFloat : MathOps<float> = { add = (+); mul = (*) }

// use of typeclass (normally ops would the 'constraint' to the left of 
// the '=>' in Haskell, but now it is an actual parameter)
let XtimesYplusZ (ops:MathOps<'t>) x y z =   //'
    ops.add (ops.mul x y) z

printfn "%d" (XtimesYplusZ mathInt 3 4 1)
printfn "%f" (XtimesYplusZ mathFloat 3.0 4.0 1.0)