Swift函数像Haskell一样执行lazy

时间:2016-06-30 03:33:01

标签: swift haskell lazy-evaluation

希望了解Swift编译链是否调用Haskell之类的函数,

let x = [1, 2, 3, 4, 5]

    func doubleMe(x: Int) -> Int {
        return x * 2
    }

    x.map(doubleMe)
    .map(doubleMe)
    .map(doubleMe)

1 个答案:

答案 0 :(得分:4)

如果您使用lazy属性,则可以使用惰性版本:

let double : (Int) -> Int = { $0 * 2 }


let result = [1, 2, 3].lazy.map(double).map(double).map(double)

for elem in result {
    print(elem)
}

print(Array(result))