简体   繁体   中英

What's the easiest way to do something like delegate multicast in 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?

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?

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.

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.

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM