"if" question of expression
I am testing a simple F # code for the expression "if", but for me this is unexpected:
> let test cab = if c then a else b;; val test : bool -> 'a -> 'a -> 'a However
> test true (printfn "a") (printfn "b");; a b val it : unit = () I expect only βaβ to be printed, but here I got both βaβ and βbβ. I wonder why this happens? Thanks!
Perhaps because both calls to the printfn function are evaluated before the test call ever occurs? If you want both function calls to be deferred until they are used, you might want lazy evaluation or macros (which F # is).
Here is the lazy version of the calculations. F # seems to require type annotations in order to use the Force method here. A bit messy, but it works.
> let test cab = if c then (a:Lazy<unit>).Force else (b:Lazy<unit>).Force;; val test : bool -> Lazy<unit> -> Lazy<unit> -> (unit -> unit) > test true (lazy (printfn "a")) (lazy (printfn "b"))();; a val it : unit = () >