替代类型类? [英] alternative to typeclasses?

查看:92
本文介绍了替代类型类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

检查 this ,正如有人所建议的那样。

我认为简短的答案是通过字典 - (就像Haskell将要引入的一样;实例的见证)。

或者改变设计,所以你不需要类型类。 (这总是让人感到痛苦,因为类型类是有史以来最好的事情,很难将它们抛在后面,但在Haskell和类型类出现之前,人们仍然设法在没有类型类型的情况下编程了40年,所以这些人做了同样的事情。)



你也可以通过 inline 静态成员约束获得一些小方法,但这很快就会变得丑陋。 / p>

下面是一个操作字典示例:

  // 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 =(*)}

//使用typeclass(通常ops会将'constraint'放在
的左边// Haskell中的'=>',但现在它是(ops:MathOps't>)xyz = //'
ops.add(ops.mul xy)z

printfn%d(实际参数)
让XtimesYplusZ (XtimesYplusZ mathInt 3 4 1)
printfn%f(XtimesYplusZ mathFloat 3.0 4.0 1.0)


haskell programmer. using F#. no typeclasses in F#. what to use when I need typeclasses?

解决方案

Do check out this as someone suggested.

I think the short answer is to pass dictionaries-of-operations (as Haskell would under the hood; the witness for the instance).

Or change the design so you don't need typeclasses. (This always feels painful, since typeclasses are the best thing ever and it's hard to leave them behind, but before Haskell and typeclasses came along, people still managed to program for 4 decades previously somehow without typeclasses, so do the same thing those folks did.)

You can also get a little ways with inline static member constraints, but that gets ugly quickly.

Here's a dictionary-of-operations example:

// 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)

这篇关于替代类型类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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