I have found a little gem here.
@tevelee: Thank you for posting it.
// [https://forums.swift.org/t/advent-of-code-2024/76301/57]
func memoize <In: Hashable, Out> (_ f: @escaping (In) -> Out) -> (In) -> Out {
var memo: [In: Out] = [:]
return {
if let result = memo[$0] {
return result
} else {
let result = f($0)
memo[$0] = result
return result
}
}
}
Could an expert disect this function for the benefit of learners?
Usage Example
func f (u:Int) -> String {
"\(u)x\(u) = \(u * u)"
}
func g (u:Int) -> String {
"\(u)x\(u)x\(u) = \(u * u * u)"
}
@main
struct Driver {
static func main () {
do {
let u = memoize (f)
print (u (2))
print (u (2))
print (u (2))
print (u (7))
print (u (7))
}
do {
let u = memoize (g)
print (u (2))
print (u (2))
print (u (2))
print (u (7))
print (u (7))
}
}
}
Output
2x2 = 4
2x2 = 4
2x2 = 4
7x7 = 49
7x7 = 49
2x2x2 = 8
2x2x2 = 8
2x2x2 = 8
7x7x7 = 343
7x7x7 = 343