简体   繁体   中英

F# Order of Execution using CPS/Partial Application

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM