gpt4 book ai didi

swift - 通用 curry map 功能

转载 作者:搜寻专家 更新时间:2023-10-31 19:35:17 25 4
gpt4 key购买 nike

我尝试将 map 函数编写为 curried 和 flipped。 (首先转换函数然后收集)。我确实编写了函数并且编译器接受了它。但我无法调用它。编译器给出没有带有提供参数的 map 函数。不管怎样,这是我写的函数:

func map <A: CollectionType, B> (f: (A.Generator.Element) -> B) -> A -> [B] {
return { map($0, f) }
}

这是测试代码:

func square(a: Int) -> Int {
return a * a
}

map(square)

注意:代码是使用 Xcode 6.3 beta 2 在 playground 中编写的

最佳答案

这里的问题是 map 不够锁定——A 是什么样的集合?您不能编写生成通用函数的通用函数——当您调用它时,必须完全确定所有占位符的类型。

这意味着您可以按照定义调用您的 map 函数,只要您完全指定 AB 的类型:

// fixes A to be an Array of Ints, and B to be an Int
let squarer: [Int]->[Int] = map(square)

squarer([1,2,3]) // returns [1,4,9]

// fixes A to be a Slice of UInts, and B to be a Double
let halver: Slice<UInt>->[Double] = map { Double($0)/2.0 }

halver([1,2,3]) // returns [0.5, 1, 1.5]

关于swift - 通用 curry map 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28888441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com