如何为带有可选参数的函数定义回调?

How is the pullback defined for a function with an optional argument?

这是一个最小的例子:

import _Differentiation

@differentiable(reverse)
func g(x: Double?) -> Double {
    if x == nil {
        return 0.0  // I don't care what this value is
    }
    else {
        return x! * x!
    }
}

@derivative(of: g)
func gVJP(x: Double?) -> (value: Double, pullback: (Double) -> Double?) {
    let value = g(x: x)
    
    func pullback(_ dOutput: Double) -> Double? {
        if x == nil {
            return nil // I don't care what this value is
        }
        else {
            return dOutput * 2.0 * x!
        }
    }
    
    return (value: value, pullback: pullback)
}

我收到以下编译器错误:

Function result's 'pullback' type does not match 'g(x:)'
1. 'pullback' does not have expected type '(Double.TangentVector) -> Optional<Double>.TangentVector' (aka '(Double) -> Optional<Double>.TangentVector')

我尝试将回调的 return 类型定义为 Optional<Double>.TangentVector,但这给了我错误,我的回调的 return 值是 incompatible with return type 'Optional<Double>.TangentVector'.

pullback 的 return 值需要转换为类型 Optional<Double>.TangentVector:

import _Differentiation

@differentiable(reverse)
func g(x: Double?) -> Double {
    if x == nil {
        return 0.0  // I don't care what this value is
    }
    else {
        return x! * x!
    }
}

@derivative(of: g)
func gVJP(x: Double?) -> (value: Double, pullback: (Double) -> Optional<Double>.TangentVector) {
    let value = g(x: x)

    func pullback(_ dOutput: Double) ->Optional<Double>.TangentVector {
        if x == nil {
            return Optional<Double>.TangentVector(nil) // I don't care what this value is
        }
        else {
            return Optional<Double>.TangentVector(dOutput * 2.0 * x!)
        }
    }

    return (value: value, pullback: pullback)
}