Search code examples
f#typeclassfunctorgeneric-programmingf#-unquote

Generalizing a new operator over many types


I am using Unquote and did not see any approximate comprison. So I decided to write one.

let inline (=~=) x y = abs x-y <  1.E-10

However the operator is not mapped onto, say Lists

let test  = [1;2] =~= [1;2]  //---> error

Is it possible to declare this operator to flow like (=) ?

Or would it require to define a new traits like 'StructuralEquality-ishness"?

Is it better to define a new operator with, say, http://code.google.com/p/fsharp-typeclasses/ ?


Solution

  • I don't know Unquote, but regarding the approximate function/operator I'm not sure if there is a way to implement it with structural comparison.

    If you want to do it "by hand", using a technique (or trick) similar to the one used for the F# Typeclasses Project, here is an example:

    type Approximate = Approximate with
        static member inline ($) (Approximate, x:^n       ) = fun (y:^n) -> float (abs (x-y)) <  1.E-10
        static member inline ($) (Approximate, x:list< ^n>) = 
            fun (y:list< ^n>) -> 
                x.Length = y.Length && (List.zip x y |> List.forall ( fun (a,b) -> (Approximate $ a) b))
    // More overloads
    let inline (=~=) x y = (Approximate $ x) y