2017-05-04 53 views
-2

也許它已經在F#中實現了?如何使用F#中的中綴運算符定義一類布爾函數?

基本上我想定義一個類與綴運營商通用的過濾功能,所以一些東西,看起來像

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

但這不是它似乎

停止由於正確的語法到錯誤System.Exception:操作不能由 完成由於較早的錯誤類型縮寫不能有 增補在2,5類型縮寫不能有成員在3,19

感謝

+4

錯誤味精就好了 – robkuz

+0

@robkuz我包括錯誤味精你 –

回答

4

你所定義有一個type abbreviation,其中,因爲錯誤將指示,既不能有擴充,也沒有成員。你可以解決這個問題通過使用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 

當然,你現在需要拆開包裝之前,布爾運算謂詞功能,包裹由功能再次之後。一個簡單的測試......

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] 
+2

我不認爲靜態運營商這是一個好主意,反正 –