2016-12-29 66 views
0

我通過了解在memoized斐波那契的(簡單)版本使用的參數工作在Advanced Swift會議解釋(跳轉到0點38分00秒)從WWDC 2014搞清楚memoize的 - 會話404

在下面memoize的函數被定義爲會話(適於夫特3)

func memoize<T: Hashable, U>(body: @escaping (T) -> U) -> (T) -> U { 
    var memo = Dictionary<T, U>() 
    return { x in 
     if let q = memo[x] { return q } 
     let r = body(x) 
     memo[x] = r 
     return r 
    } 
} 

它將包裹簡單的函數,例如:

let ntos = memoize {(n: Int) -> String in 
    print("Must evaluate something") 
    return "\(n)" 
} 

print(ntos(3)) 
print(ntos(3)) 
print(ntos(30)) 

輸出:

Must evaluate something 
3 
3 
Must evaluate something 
30 

類型NTOS的是(Int) -> String所以在memoize的所述T變得IntU變得String

但對於斐波那契功能,例如蘋果使用的是

let fibonacci = memoize { 
    fibonacci, n in 
    n < 2 ? Double(n) : fibonacci(n: n - 1) + fibonacci(n: n - 2) 
} 

在這裏我不知道什麼類型的T,和U適應?以及函數如何表現遞歸性質?如何將閉合參數聲明fibonacci, n轉換爲memoize (T) -> U體型參數?

爲什麼斐波納契甚至在閉包的定義中傳遞給記憶呢?我認爲這與curried函數的想法有關(在Swift 3中被閉包取代),但是實現語法不會爲我點擊。

+0

可能相關:http://stackoverflow.com/questions/37690663/explanation-for-swift-memoization-call-syntax。 –

回答

0

我決定把它更進一步,寫了滿滿fledges walk through of memoize

+0

看起來像一個徹底的步行,不錯的工作!但請注意,在此SO(僅限於鏈接的答案)(http://meta.stackexchange.com/questions/8231/are-answers-that-just-contain-links-elsewhere-really-good-answers)即使它是你自己的鏈接,我們也不知道它是否會在幾年後仍然存在);你能引用/突出你的博客文章中的一些部分,這樣至少可以簡單地回答這個問題嗎?你可以參考你的博客文章以獲得更詳細的報道。 – dfri