在F#中执行委托多播等最简单的方法是什么 [英] What's the easiest way to do something like delegate multicast in F#

查看:75
本文介绍了在F#中执行委托多播等最简单的方法是什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当前,我使用它并且效果很好:

Currently I use this and it works fine:

let mutable notify = fun x -> x
let wrap f i = f(i); i

let a x = printf "%A" x
notify <- notify >> (wrap a)

notify "ss"

还有其他更好的方法吗?

Are there any other better approach?

为什么不起作用?

let mutable notify = fun x -> x
let wrap f i = f(i); i

let a x = printf "%A" x  
let d x =
    (notify >> (wrap a)) x
notify <- d

notify "ss"

我不确定为什么第一个示例不会触发无限循环,而第二个示例会触发无限循环.

I am not sure why the first example doesn't trigger endless loop, but the second does.

似乎可变函数变量(无点函数)的行为与我预期的不同.从哪里可以学到更多关于这个主题的东西?

It seems mutable function variable (point free function) has different behaviour than I expected. Where can I learn more from regarding this topic?

推荐答案

您是否不想使用MulticastDelegate?

type D<'T> = delegate of 'T -> 'T
let mutable notify = D<string>(fun x -> x)
let wrap f i = f(i); i
let a x = printfn "%A" x
notify <- Delegate.Combine(notify, D<string>(wrap a)) :?> _
notify.Invoke "ss"

您的第二个示例失败,因为d调用了notify,该循环无限递归.

Your second example fails because d calls notify, which recurses infinitely.

这篇关于在F#中执行委托多播等最简单的方法是什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆