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

标签 f# monads custom-operator

我想在我的计算表达式上定义一些自定义运算符,但无法使其工作

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 }

顺便说一句,将 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 tests中有很多示例展示了如何定义类似zip(和其他)的自定义操作。)

关于f# - 如何在计算表达式中定义自定义运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39965684/

相关文章:

swift : Custom operator to update dictionary value

F# 事务管理

algorithm - Haskell while循环哪里递归根本行不通?

f# - ContainsKey 返回单位而不是 bool 值?

swift - 为什么 Swift 允许双重可选?

haskell - "evaluate"和 "return $!"和有什么区别?

swift - 如何快速实现自定义运算符 []

c++ - 为什么选择我的自定义操作的 CPU 实现?

f# - 在F#中,是否可以使用tryParse函数来推断目标类型

f# - 如何模仿 F# 编译器类型检查?