开发者

F# block arguments

C# has anonymous delegates. So I can write:

public vois foo(string d, Action t){
    t();
}

In ruby:

def foo d
  yield
end

How to开发者_StackOverflow社区 do the same in F#? Prefered syntax is:

foo "dfdfdf" { do something here }

Thanks


Your first example isn't an anonymous method -- it's just passing and calling through a delegate (which might refer to a named or an anonymous method). To do this in F#, just provide and call a function argument:

let foo n f = f n

let square n = n * n
let result = foo 123 square
printfn "%A" result

To create the equivalent of an anonymous method in F#, use the fun keyword:

let result2 = foo 123 (fun n -> n * n)


Have a look at this article about Higher Order Functions in F#. Higher Order Functions are functions which accept other functions as arguments, and sound like the concept you are describing.


open System

// create a function that expects an Action delegate and executes it
let foo (actionDelegate:Action) (s:String) = actionDelegate.Invoke();

// create a function that meets Action delegate
let ActionFunction param = Console.Write("Action in action")

// call foo passing ActionFunction
foo (new Action(ActionFunction)) "my string"
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜