What's the closest thing to Haskell GADTs and typeclasses in F#?

后端 未结 2 1028
旧时难觅i
旧时难觅i 2020-12-31 19:32

F# is an ML with OOP. What\'s the closest it comes to Haskell generalized algebraic data types and typeclasses?

2条回答
  •  情深已故
    2020-12-31 20:27

    In F#, you often use interfaces and inheritance for these purposes.

    For examples' sake, here is a simple typeclass using interfaces and object expressions:

    /// Typeclass
    type MathOps<'T> =
        abstract member Add : 'T -> 'T -> 'T
        abstract member Mul : 'T -> 'T -> 'T
    
    /// An instance for int
    let mathInt = 
        { new MathOps with
           member __.Add x y = x + y
           member __.Mul x y = x * y }
    
    /// An instance for float
    let mathFloat = 
        { new MathOps with
           member __.Add x y = x + y
           member __.Mul x y = x * y }
    
    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 may not look very beautiful, but it's F#-ish way to do it. For a more Haskell-like solution which uses a dictionary-of-operations, you can have a look at this nice answer.

提交回复
热议问题