Search code examples
filterf#infix-notation

how to define a class of boolean functions with infix operators in F#?


Maybe it's already implemented in F# ?

basically i would like to define a class of generic filter functions with infix operators, so something which would look like

type Filter<'T> = ('T -> bool) with 
     static member (|*) (f:Filter<'T>) (g:Filter<'T>) = (fun x -> (f x) || 
     (g x)) // OR operator

but this is not the right syntax it seems

Stopped due to error  System.Exception: Operation could not be completed due to earlier error  Type abbreviations cannot have augmentations at 2,5  Type abbreviations cannot have members at 3,19

thanks


Solution

  • What you are defining there is a type abbreviation, which, as the errors will indicate, can neither have augmentations nor members. You could fix that by using a single case discriminated union:

    type Filter<'T> = Filter of ('T -> bool) with 
         static member (|* ) (Filter f, Filter g) =
            Filter(fun x -> f x || g x) // OR operator
    

    Of course, you now need to unwrap the predicate function prior to the boolean operation, and wrap the composed function again afterwards. A simple test...

    let odd x = x % 2 <> 0
    let big x = x > 10
    let (Filter f) = Filter odd |* Filter big in [8..12] |> List.filter f
    // val it : int list = [9; 11; 12]