ahmed ansari
ahmed ansari

Reputation: 129

alternative to typeclasses?

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

Upvotes: 12

Views: 2031

Answers (1)

Brian
Brian

Reputation: 118865

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)

Upvotes: 20

Related Questions