部分应用函数并在运行时动态调用该函数
Partially apply a function and dynamically call that function at runtime
使用 F#,如果我部分应用这样的函数:
let sleep x = Async.Sleep x |> Async.RunSynchronously
let log date message= printfn "%s %s" date message
let getDate = DateTime.Now.ToString()
let logg = log getDate
logg "First"
sleep 1000
logg "Second"
sleep 1000
打印:
30/11/2018 19:54:25 First
30/11/2018 19:54:25 Second
对 getDate 的调用似乎在它生成的新部分函数中转换为实际日期。这是为什么,是否可以让它在每次调用此日志函数时调用 getDate?
so I have to declare all methods in the chain that use getDate with () after them, and call them accordingly to make them reevaluate when called, otherwise they become fixed variables. Is that right?
我会反过来说:let
总是绑定一个值,但在 let getDate ()
或 let sleep x
的情况下,这些值恰好是函数;它们基本上等同于
let sleep = fun x -> Async.Sleep x |> Async.RunSynchronously
let getDate = fun () -> DateTime.Now.ToString()
当然,如果您检查字节码,实际上不会发生这种情况,但 "morally" 确实如此。使用这些定义
let sleep = fun x -> Async.Sleep x |> Async.RunSynchronously
let log = fun date message -> printfn "%s %s" date message
let getDate = fun () -> DateTime.Now.ToString()
let logg = fun x -> log (getDate ()) x
logg "First"
sleep 1000
logg "Second"
sleep 1000
你会得到相同的输出:
30/11/2018 19:59:40 First
30/11/2018 19:59:41 Second
使用 F#,如果我部分应用这样的函数:
let sleep x = Async.Sleep x |> Async.RunSynchronously
let log date message= printfn "%s %s" date message
let getDate = DateTime.Now.ToString()
let logg = log getDate
logg "First"
sleep 1000
logg "Second"
sleep 1000
打印:
30/11/2018 19:54:25 First
30/11/2018 19:54:25 Second
对 getDate 的调用似乎在它生成的新部分函数中转换为实际日期。这是为什么,是否可以让它在每次调用此日志函数时调用 getDate?
so I have to declare all methods in the chain that use getDate with () after them, and call them accordingly to make them reevaluate when called, otherwise they become fixed variables. Is that right?
我会反过来说:let
总是绑定一个值,但在 let getDate ()
或 let sleep x
的情况下,这些值恰好是函数;它们基本上等同于
let sleep = fun x -> Async.Sleep x |> Async.RunSynchronously
let getDate = fun () -> DateTime.Now.ToString()
当然,如果您检查字节码,实际上不会发生这种情况,但 "morally" 确实如此。使用这些定义
let sleep = fun x -> Async.Sleep x |> Async.RunSynchronously
let log = fun date message -> printfn "%s %s" date message
let getDate = fun () -> DateTime.Now.ToString()
let logg = fun x -> log (getDate ()) x
logg "First"
sleep 1000
logg "Second"
sleep 1000
你会得到相同的输出:
30/11/2018 19:59:40 First
30/11/2018 19:59:41 Second