繁体   English   中英

Swift更高阶函数(Church pair aka cons),通用参数类型不接受输入参数类型

[英]Swift higher order function (Church pair aka cons) with generic parameter types not accepting input parameter types

我正在搞乱Swift 2.1中的函数式编程,尝试实现Church编码对/ cons函数(在无类型lambda演算中的 cons =λxλyλffxy),我读过的在早期版本的Swift中无法完成。

使用泛型它看起来像

func cons<S,T,U>(x:S,_ y:T) -> ((S,T) -> U) -> U
{
    return { (f:((S,T) -> U)) -> U in return f(x,y)}
}

cons(1,2)
//error: cannot invoke 'cons' with an argument list of type '(Int, Int)'
//note: expected an argument list of type '(S, T)'

哪个不起作用,并给出一个我无法理解的错误(当然,类型(Int,Int)的参数列表可以匹配泛型类型变量(S,T)?)

如果你摆脱了泛型类型,并将它们全部声明为Ints,那么该函数可以正常工作,但当然我们希望能够将长度超过2的列表组合在一起; 例如,使用(Int,Int) - > Int来构造长度为3的列表。

另一种选择是将所有内容输入为Any (请参阅Type和AnyObject的类型转换 ),但我也无法做到这一点。

你有什么想法? 这在Swift中可能吗? 我确信有更简单的方法来实现cons / car / cdr ,但我对Church编码特别感兴趣,其中list元素是匿名函数(lambdas)的参数。

func cons<S,T,U>(x:S,_ y:T) -> ((S,T) -> U) -> U
{
    return { (f:((S,T) -> U)) -> U in return f(x,y)}
}

let i: ((Int,Int)->Int)->Int = cons(1,2)
let d: ((Int,Int)->Double)->Double = cons(2,3)
let e: ((Double,Int)->String)->String = cons(2.2, 1)
let e: ((Double,Int)->Double)->Double = cons(2.2, 1)

stil类型之一是'额外'类型,无法通过compilator推断。 如果您定义类型,您可以看到,并非所有组合都有效。 只需定义输出类型,编译器应该很开心

func cons<S,T, U>(x:S,_ y:T, outptAs: U.Type) -> ((S,T) -> U ) -> U
{
    return { (f:((S,T) -> U)) -> U in return f(x,y) }
}

let i = cons(1.2 ,"A", outptAs: Int.self)
let j = cons("alfa","beta", outptAs: Double.self)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM