Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"if" expression question

Tags:

f#

I test some simple F# code for "if" expression, but the result is unexpected for me:

> let test c a b = 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'd expect only "a" is printed out but here I got both "a" and "b". I wonder why it comes out this way? Thanks!

like image 453
Here Avatar asked Dec 04 '22 12:12

Here


2 Answers

Hao is correct. You have to wrap those expressions in functions to make them lazy. Try this.

let test c a b = if c then a() else b();;
test true (fun () -> printfn "a") (fun () -> printfn "b");;
like image 81
gradbot Avatar answered Jan 21 '23 01:01

gradbot


Possibly because both printfn function calls are evaluated before the test call ever occurs? If you want both the function calls to be delayed until they're actually used, you might want lazy computation or macros (which F# doesn't have).

like image 35
hao Avatar answered Jan 21 '23 02:01

hao