Swift Functional Programming Tutorial
这几天学习了一下函数式编程,简直是思维上的颠覆,代码可以这样思考。
这篇文章简略的Filter和reduce实现
func myFilter<T>(source: [T], predicate:(T) -> Bool) -> [T] {
var result = [T]()
for i in source {
if predicate(i) {
result.append(i)
}
}
return result
}
extension Array {
func myReduce<T, U>(seed:U, combiner:(U, T) -> U) -> U {
var current = seed
for item in self {
current = combiner(current, item as T)
}
return current
}
}
最后给出一个例子
let words = ["Cat", "Chicken", "fish", "Dog",
"Mouse", "Guinea Pig", "monkey"]
实现对单词的首字母归类
[("C", ["Cat", "Chicken"]), ("F", ["fish"]), ("D", ["Dog"]), ("M", ["Mouse", "monkey"]), ("G", ["Guinea Pig"])]
我给出的常规的实现
typealias Entry = (Character, [String])
func buildIndex(words:[String]) -> [Entry]{
var entryList = [Entry]()
for word in words {
let firstLetter = word.uppercaseString[word.startIndex]
var find = false
for (index, entry) in entryList.enumerate() {
if firstLetter == entry.0 {
find = true
/*
entry.1.append(word)
//重点!!一定要记住值类型和引用类型
//entry是值类型
entryList[index] = entry
*/
//优化
entryList[index].1.append(word)
}
}
if !find {
let entry : (Character, [String]) = (firstLetter, [word])
entryList.append(entry)
}
}
return entryList
}
改为函数式编程的实现
let compute = words.reduce([]) { (var arr, word) -> [Character] in
let letter = word.uppercaseString[word.startIndex]
if !arr.contains(letter) {
arr.append(letter)
}
return arr
}.map { (letter) -> Entry in
return (letter, words.filter({ (word) -> Bool in
return word.uppercaseString[word.startIndex] == letter
}))
}
觉得比文章的实现要好
网友评论