如何在计算表达式中定义自定义运算符



我想在我的计算表达式上定义一些自定义运算符,但是不能使它工作

type ZipSeq() =
    [<CustomOperation("<*>")>]
    member this.Apply f s = 
        f |> Seq.zip s |> Seq.map (fun (y, x) -> x(y))
    member this.Return x = 
        Seq.initInfinite (fun _ -> x)
    // (a -> b) -> seq<a> -> seq<b>
    [<CustomOperation("<!>")>]
    member this.Map f s =
        this.Apply (this.Return f) s
let zipSeq = new ZipSeq()
let f (a : float) = a * a
let s = seq { yield 1. }
// seq<b>
let h1 = zipSeq.Map f s
//thinking h1 should be the same as h2
//but compilation error : ` This value is not a function and cannot be applied`
let h2 = zipSeq { return f <!> s }

Btw,将member this.Map f s ...更改为member this.Map (f, s) ...会产生相同的错误。

正如在注释中已经提到的,计算表达式和自定义运算符是两个正交的语言特性,它们不以任何方式相互作用。如果你想使用自定义操作符,你可以定义自定义操作符并使用它(你可以将它们定义为类型的成员来限制它们的作用域,或者定义为必须显式打开的模块的成员)。

如果您对使用计算表达式来实现类似于应用程序编程风格的东西感兴趣,那么值得注意的是,可以在计算表达式中定义"类似zip"的操作。这使您可以使用良好的语法编写压缩:

zipSeq {
  for x in [1; 2; 3] do
  zip y in ['a'; 'b'; 'c'] 
  yield x, y }

这产生一个具有[1,a; 2,b; 3,c]的序列。允许您这样做的计算构建器定义如下所示:

type SeqZipBuilder() = 
    member x.For(ev:seq<'T>, loop:('T -> #seq<'U>)) : seq<'U> = 
      Seq.collect loop ev
    member x.Yield(v:'T) : seq<'T> = seq [v]
    [<CustomOperation("zip",IsLikeZip=true)>]
    member x.Zip
      ( outerSource:seq<'Outer>,  innerSource:seq<'Inner>,  
        resultSelector:('Outer -> 'Inner -> 'Result)) : seq<'Result> =
        Seq.map2 resultSelector outerSource innerSource
let zipSeq = SeqZipBuilder()

(据我所知,这没有很好的文档记录,但是在f#的repo测试中有一堆例子显示了如何定义类似zip(和其他)的自定义操作。)

最新更新