tags:

views:

286

answers:

3

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.

+2  A: 

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")    
missingfaktor
I think he's looking for lambda usage, I'd put the printf as a lambda
Mauricio Scheffer
@Scheffer : Edited as per your suggestion. Thanks! :)
missingfaktor
not quite Ruby, but it will do
Geo
minor typo: printfln -> printfn
Mauricio Scheffer
@Scheffer : Thanks again! :)
missingfaktor
2 |> times (fun _ -> printfn "Hello")
Dario
by the way, is it possible for that lambda to have more than one line? In Ruby I have braces to delimit it's body.
Geo
I downvoted now because the answer is wrong. Earlier I edited to fix, but you reverted that, and also have added a new, also-wrong answer. The new code does not even compile; the old code does the wrong thing.
Brian
@Brain : Sorry. I fixed the code as per your last edit.
missingfaktor
@Geo : Brian has answered your question in this thread : http://stackoverflow.com/questions/814278/how-to-do-multiline-lambda-expressions-in-f
missingfaktor
+10  A: 

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.

Mauricio Scheffer
what does the `_` in the lambda stand for?
Geo
It is a wildcard. The _ will match any value and is a wayof telling the compiler that you’re not interested in using this value.
missingfaktor
+1 - for functional style, not imperative one
Matajon
+9  A: 

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")
Brian