如何在 F# 中使用中缀运算符定义 class 布尔函数?
how to define a class of boolean functions with infix operators in F#?
也许它已经在 F# 中实现了?
基本上我想用中缀运算符定义一个 class 通用过滤器函数,所以看起来像
type Filter<'T> = ('T -> bool) with
static member (|*) (f:Filter<'T>) (g:Filter<'T>) = (fun x -> (f x) ||
(g x)) // OR operator
但这似乎不是正确的语法
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
谢谢
你定义的是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
当然,您现在需要在布尔运算之前解包谓词函数,然后再包装组合函数。一个简单的测试...
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]
也许它已经在 F# 中实现了?
基本上我想用中缀运算符定义一个 class 通用过滤器函数,所以看起来像
type Filter<'T> = ('T -> bool) with
static member (|*) (f:Filter<'T>) (g:Filter<'T>) = (fun x -> (f x) ||
(g x)) // OR operator
但这似乎不是正确的语法
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
谢谢
你定义的是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
当然,您现在需要在布尔运算之前解包谓词函数,然后再包装组合函数。一个简单的测试...
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]