Why does this print "DIV/0" first and "2" second?
let printZero = printfn "DIV/0"
let printSuccess x = printfn "%d" x
let div ifZero success x y =
if y = 0
then ifZero
else x / y |> success
let printDiv = div printZero printSuccess
printDiv 8 4
printDiv 10 0
printfn "DIV/0"
will write to the console immediately, returning unit
. So this line:
let printZero = printfn "DIV/0"
...will immediately write DIV/0
and binds unit
to the value printZero
. Later when you call your div
function with y = 0
, you just return that value.
What you want is for printZero
to be a function. As that function doesn't need any value as input, you can use unit
here too (represented as ()
) - so you have a function of type unit -> unit
:
let printZero() = printfn "DIV/0"
let printSuccess x = printfn "%d" x
let div ifZero success x y =
if y = 0
then ifZero()
else x / y |> success