开发者

alternative to typeclasses?

开发者 https://www.devze.com 2023-01-15 00:21 出处:网络
haskell programmer. using F#. no typeclasses in F#. what to use when I need t开发者_运维知识库ypeclasses?Do check out this as someone suggested.

haskell programmer. using F#. no typeclasses in F#. what to use when I need t开发者_运维知识库ypeclasses?


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号