美文网首页
函数式编程学习

函数式编程学习

作者: peerben | 来源:发表于2016-03-12 11:58 被阅读34次

    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
        }))
    }
    

    觉得比文章的实现要好

    相关文章

      网友评论

          本文标题:函数式编程学习

          本文链接:https://www.haomeiwen.com/subject/haexlttx.html