如何在Swift中使用多个参数制作通用备忘录功能?

问题描述

我正在制作国际象棋引擎(在很大程度上依赖于函数编程),并且它需要在每个步骤进行记忆以避免重新计算。我阅读了这篇文章,该文章提供了用于记忆的通用功能

http://simon-fortelny.com/2017/07/04/GenericMemoization/

代码

    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
    }

现在,我想扩展该函数以接受多个输入参数。我尝试使用像这样的可变参数:

    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
    }

但是我遇到2个错误

  1. 表达式类型不明确,没有更多上下文
  2. 无法将类型为[[T]”的数组作为类型为“ T”的可变参数传递

screenshot

知道我在做什么错以及如何使其支持多个参数吗?

解决方法

感谢大家的评论。我最终弄清楚了(由于这个answer

我创建了一个传递给函数的结构,而不是将多个参数作为可变参数传递给该函数。

struct PairState<T: Hashable,U: Hashable>: Hashable {
    let first: T
    let second: U
}