這個問題是關於函數式編程的。示例代碼在F#中。用延續傳遞風格重寫f#函數
假設我有一個簡單的函數f:
let f x =
x + 1
現在(的原因,我不想解釋,涉及到線程),我必須轉動F成函數與延續:
let f x cont =
cont (x+1)
現在我必須重寫所有調用f的函數,這些函數將不再編譯。
舉例來說,如果我有這樣的功能
let g x =
let res = f x
res + 2
我必須重寫G作爲
let g x cont =
f x (fun res ->
cont (res + 2))
這變得複雜了,但仍然是manaegable。
但問題是:如何重寫下面的一段代碼?
let lmapped = [ for x in l do
let res = f x
yield res + 1 ]
if List.isEmpty lmapped then
...
有沒有簡單的方法來重寫它? (可能避免一個明確的遞歸函數,如「let rec ...」)謝謝