Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

alternative to typeclasses?

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

like image 734
ahmed ansari Avatar asked Sep 08 '10 02:09

ahmed ansari


1 Answers

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)
like image 193
Brian Avatar answered Nov 04 '22 04:11

Brian