What's the easiest way to do something like delegate multicast in F#

被刻印的时光 ゝ 提交于 2019-12-11 05:05:28

问题


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?

and why this doesn't work?

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?


回答1:


Do you not want to use 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"

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




回答2:


I believe that the way to compose multiple handlers in the functional programming paradigm is for each handler to tail-call its first argument, passing the remainder of the arguments. Then curry that with another handler, forming a chain or singly-linked list of handlers.




回答3:


Here's one straightforward alternative. If you want to represent a list of functions to call, then why not just keep a (mutable) list of functions?

let handlers = ResizeArray()
let notify x = 
    for f in handlers do
        f x

handlers.Add(fun x -> printf "%A" x)

notify "ss"


来源:https://stackoverflow.com/questions/17708318/whats-the-easiest-way-to-do-something-like-delegate-multicast-in-f

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!