2017-05-04 51 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

我不认为静态运营商这是一个好主意,反正 –