I'm learning F#, and I'd like to know how a snippet like this could be written using F# only:
2.times {
puts "hello"
}
If you can explain how/if functions that take blocks are possible in F#, that would be great as well.
I'm learning F#, and I'd like to know how a snippet like this could be written using F# only:
2.times {
puts "hello"
}
If you can explain how/if functions that take blocks are possible in F#, that would be great as well.
The times function can be written as :
let times act n =
for i in 1 .. n do
act()
and can be invoked as :
2 |> times (fun () -> printfn "Hello")
Here's one that uses a lambda (basically a ruby block):
{1..2} |> Seq.iter (fun _ -> printfn "hello")
Here the Seq.iter
function is taking a lambda as parameter, which is executed in each iteration.
I don't have a compiler handy, so someone please fix this up if it doesn't compile. Here's a way to define the corresponding F# extension member.
type System.Int32 with
member this.Times(act) =
for i in 1..this do
act()
(2).Times (fun() -> printfn "Hello")