标签:style http io ar color os sp java for
今天解决一下 Higher Order Functions: Map, Filter, Reduce and more – Part 1 中最后的13个练习题,主要是关于闭包的(咦不对啊我明明是想看集合方面内容的。。。)。
func applyTwice(f:(Float -> Float),x:Float) -> Float {
return f(f(x))
}
// recursive version
func applyKTimes(f:(Float -> Float), x:Float, k:Int) -> Float
{
return k > 0 ? applyKTimes(f, f(x), k - 1) : x
}
// unrolled by hand
func applyKTimes(f:(Float -> Float),x:Float,k:Int) -> Float {
var y : Float = x
for _ in 0..<k {
y = f(y)
}
return y
}
func getKthPower(x:Float, k:Int) -> Float{
return applyKTimes( {x * $0}, 1, k) // {x * $0} => {p in return x * p}
}
getKthPower(2.0, 3) // 8.0
class User {
var name: String?
var age : Int?
init (name: String, age:Int) {
self.name = name
self.age = age
}
}
var user1 = User(name: "WHY1", age: 22)
var user2 = User(name: "WHY2", age: 23)
var user3 = User(name: "WHY3", age: 24)
var user4 = User(name: "WHY4", age: 25)
var users = [user1,user2,user3,user4]
var names: [String] = []
users.map({(user:User) in names.append(user.name!)})
println(names) // [WHY1, WHY2, WHY3, WHY4]
var users = [["name":"WHY1","age":"22"],["name":"WHY2","age":"23"],
["name":"WHY3","age":"24"],["name":"WHY4","age":"25"]]
var result = users.map({ (userDic:[String:String]) -> User in
return User(name: userDic["name"]!, age:userDic["age"]!.toInt()!)
})
var nums = [1,2,4,8,23,45,89,127]
var odds = nums.filter({ $0 % 2 == 0 }) // 2 4 8
var strs = ["2333","1223","callmewhy","callherhh"]
var intables = strs.filter({ $0.toInt() != nil }) // ["2333", "1223"]
import UIKit
var view1 = UIView()
var view2 = UIView()
var view3 = UILabel()
var view4 = UIView()
var views = [view1,view2,view3,view4]
var labels = views.filter({ $0.isKindOfClass(UILabel) }) // view3
var strs = ["str1","str2","str3","str4"]
var str = strs.reduce("", combine: { "\($0)\n\($1)" })
println(str)
var ints = [1,2,3,4,5,6]
var maxValue = ints.reduce(Int.min, { max($0, $1) }) // 6
var array = [1,2,3,4,6]
var mean = array.reduce(0, combine: {$0 + Float($1) / Float(array.count)}) // make division 5 times
// TODO
// TODO
标签:style http io ar color os sp java for
原文地址:http://blog.csdn.net/pleasecallmewhy/article/details/41320899