[英]How to make a generic memoization function with multiple arguments in Swift?
I am making a chess engine (which heavily relies on functional programming) and it requires memoization at every step to avoid re-computation.我正在制作一个国际象棋引擎(它严重依赖于函数式编程),它需要在每一步都进行记忆以避免重新计算。 I read this article which provided a generic function for memoization:
我读了这篇文章,它提供了一个通用的记忆功能:
http://simon-fortelny.com/2017/07/04/GenericMemoization/ http://simon-fortelny.com/2017/07/04/GenericMemoization/
Code:代码:
func memoize<T: Hashable, U>(function: @escaping (T) -> U) -> (T) -> U {
var cache : [T: U] = [:]
func memoWrapper(input: T) -> U {
if let cacheValue = cache[input] {
return cacheValue
}
let newVal = function(input)
cache[input] = newVal
return newVal
}
return memoWrapper
}
Now I want to extend that function to accept multiple input parameters.现在我想扩展该函数以接受多个输入参数。 I tried using variadic arguments like this:
我尝试使用这样的可变参数:
func memoize<T: Hashable, U>(function: @escaping (T...) -> U) -> (T...) -> U {
var cache : [[T]: U] = [:]
func memoWrapper(input: T...) -> U {
if let cacheValue = cache[input] {
return cacheValue
}
let newVal = function(input)
cache[input] = newVal
return newVal
}
return memoWrapper
}
But I'm getting 2 errors:但我收到 2 个错误:
Any idea what I'm doing wrong and how to make it support multiple arguments?知道我做错了什么以及如何让它支持多个参数吗?
Thanks for the comments guys.谢谢你们的评论。 I ended up figuring it out (thanks to this answer )
我最终弄明白了(感谢这个答案)
I created a struct to pass to the function instead of multiple parameters as variadic arguments.我创建了一个结构来传递给函数而不是多个参数作为可变参数。
struct PairState<T: Hashable, U: Hashable>: Hashable {
let first: T
let second: U
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.