zoukankan      html  css  js  c++  java
  • swift之函数式编程(四)

    文章内容来自《Functional Programing in Swift》,具体内容请到书中查阅

    Map, Filter, Reduce

    Functions that take functions as arguments are sometimes called higher- order functions. 

    higher-order function(高阶函数)就是说函数可以作为另一个函数的参数。

    在本章,我们将介绍一下swift标准库中在数组方面的一些相关的高阶函数,先介绍一些比较普通的然后介绍如何把这些泛型的操作组织成一个比较复杂的操作。

    Introducing Generics (泛型)

    // 函数:返回 对原来的数组的每个元素进行加1后的数组
    func incrementArray(xs: [Int]) -> [Int] { var result: [Int] = [] for x in xs { result.append(x + 1) } return result }
    // 函数:返回 对原来的数组的每个元素进行乘2后的数组
    func doubleArray1(xs: [Int]) -> [Int] { var result: [Int] = [] for x in xs { result.append(x * 2) } return result }

     你会发现这两个方法中有很多相似的代码,能够将这些不同的地方抽象出来,写成一个单一,更普通的函数的方式么?就如下面:

    func computeIntArray(xs: [Int]) -> [Int] { 
        var result: [Int] = []
        for x in xs {
            result.append(/* something using x */) }
        return result 
    }    
    

     为了完成上面的定义,我们将需要一个新的参数用来抽象出这些不同的地方:

    func computeIntArray(xs: [Int], f: Int -> Int) -> [Int] { 
        var result: [Int] = []
        for x in xs {
            result.append(f(x)) 
        }
        return result 
    }    
    

     那么之前的代码将变成下面:

    func doubleArray2(xs: [Int]) -> [Int] {
         return computeIntArray(xs) { x in x * 2 }
    }
    

     注意在调用computeIntArray的时候,我们使用过了尾闭包(trailing closures )语法

    但是这个computeIntArray还不是很灵活,如果我们支持计算一个数组中的元素是不是偶数:

    func isEvenArray(xs: [Int]) -> [Bool] { 
        computeIntArray(xs) { x in x % 2 == 0 }
    }
    

     不幸的是,这段代码会报一个类型错误。那么我们该如何解决呢?或许我们会这样做:

    func computeBoolArray(xs: [Int], f: Int -> Bool) -> [Bool] { 
        let result: [Bool] = []
        for x in xs {
            result.append(f(x))
         }
        return result
     }
    

     但是这样还是不好,假如我们需要计算的是String?难道我们要定义另外一个高阶函数,参数类型为 Int->String  ?

    we will say "NO"

    幸好,这有解决办法:我们可以使用泛型 (generics):

    func genericComputeArray<U>(xs: [Int], f: Int -> U) -> [U] { 
        var result: [U] = []
        for x in xs {
            result.append(f(x)) 
        }
        return result 
    }
    

     但是你会发现我们这边还是有个[Int],so:

    func map<T, U>(xs: [T], f: T -> U) -> [U] { 
        var result: [U] = []
        for x in xs {
            result.append(f(x)) 
        }
        return result 
    }
    

    下面我们对上面的一个函数进行改造:

    func computeIntArray<T>(xs: [Int], f: Int -> T) -> [T] { 
        return map(xs, f)
    }

     map这个函数的早已在swift的标准库中定义了。下面就是用swift中的map的调用:

    func doubleArray3(xs: [Int]) -> [Int] { 
        return xs.map { x in 2 * x }
    }
    

     在本章中我们不建议你自定义map,但是我们想说的是定义map其实也不是那么神奇的一件事,你完全可以自己自定义。

    Filter

    map函数并不是swift标准Array库中通过使用 泛型 唯一的方法。在接下来的节中,我们将会陆续介绍其他的

    假定我们有下面一个数组:

    let exampleFiles = ["README.md", "HelloWorld.swift", "HelloSwift.swift", "FlappyBird.swift"]
    

     现在假定我们需要元素的后缀是.swift的数组:

    func getSwiftFiles(files: [String]) -> [String] { 
        var result: [String] = []
        for file in files {
            if file.hasSuffix(".swift") { 
                result.append(file)
            }  
       }
        return result
     }

     为了满足更多的需求,我们使用泛型定义了:

    func filter<T>(xs: [T], check: T -> Bool) -> [T] {
        var result: [T] = []
        for x in xs {
            if check(x) {
                result.append(x) 
            }
        }
        return result
    }

     那么这个时候定义getSwiftFiles就Filter而言变得更加容易:

    func getSwiftFiles2(files: [String]) -> [String] {
        return filter(files) { file in file.hasSuffix(".swift") }
    }

     就如map一样,filter也早已在swift的标准库中定义了:

    exampleFiles.filter { file in file.hasSuffix(".swift") }
    

     现在你可能想知道:有没有一个更通用的函数----定义包含了 map 和fiter的函数?这就是接下来我们要讲的。

    Reduce

    来一起看下面这个sum函数

    func sum(xs: [Int]) -> Int {
        var result: Int = 0
        for x in xs {
            result += x 
        }
        return result
     }

    下面我们使用下这个函数

    let xs = [1,2,3,4]

    sum(xs)   // 结果为10

    一个和sum比较类似的函数product:

    func product(xs: [Int]) -> Int { 
        var result: Int = 1
        for x in xs {
            result = x * result
         }
        return result 
    }

    或者类似的一个,把数组中的字符串串起来,返回一个字符串:

    func concatenate(xs: [String]) -> String { 
        var result: String = ""
        for x in xs {
            result += x 
        }
        return result 
    }

     或者我们:

    func prettyPrintArray(xs: [String]) -> String {
        var result: String = "Entries in the array xs:
    " 
        for x in xs {
            result=" "+result+x+"
    " 
        }
        return result 
    }

    上面的这些函数有公共的地方么?他们都初始化了一个变量result,他们都通过迭代xs里面的元素 以某种方式进行更新这个reslut。用泛型函数来描绘这个模式,我们需要提炼出2条信息:

    初始化一个变量,在迭代中更新这个变量。

    鉴于此,我们通过定义reduct函数来描述这个模式:

    func reduce<A, R>(arr: [A], initialValue: R,combine: (R, A) -> R) -> R {
        var result = initialValue
         for i in arr {
            result = combine(result, i) 
        }
        return result 
    }

     一开始对于这个reduce会有一点难读。它在两方面使用泛型:输入数组的类型[A],resulst 的类型R。在函数式编程中如OCaml和Haskell中,reduce函数被叫做fold或者fold_right

    func sumUsingReduce(xs: [Int]) -> Int {
        return reduce(xs, 0) { result, x in result + x } // 使用了尾闭包
    }

    我们甚至可以简写成:

    func productUsingReduce(xs: [Int]) -> Int {
         return reduce(xs, 1, *)
    }
    
    
    func concatUsingReduce(xs: [String]) -> String { 
        return reduce(xs, "", +)
    }

     在一次,reduce是array的一个扩展,所以我们在使用reduce(xs, initialValue,combine)变为:xs.reduce(initialValue, combine)

    reduce: iterating over an array to compute a result. 

    Putting It All Together 

    struct City{
        let name: String
        let population: Int
    }
    
    let paris = City(name: "Paris", population: 2243)
    let madrid = City(name: "Madrid", population: 3216)
    let amsterdam = City(name: "Amsterdam", population: 811)
    let berlin = City(name: "Berlin", population: 3397)
    
    let cities = [paris, madrid, amsterdam, berlin]
    
    
    func scale(city: City) -> City {
        return City(name: city.name, population: city.population * 1000)
    }
    
    cities.filter({ city in city.population > 1000 }) .map(scale).reduce("City: Population") { 
        result, c in
            return result + "
    " + "(c.name) : (c.population)"
    }
        

    Generics vs. the Any Type 

     两者都可以在函数定义中接受不同类型的参数,然而又有所不同:

    generics can be used to define flexible functions, the types of which are still checked by the compiler; the Any type can be used to dodge Swift’s type system (and should be avoided whenever possible). 

    func noOp<T>(x: T) -> T { 
        return x
    }
    

     用Any:

    func noOpAny(x: Any) -> Any { 
        return x
    }
    

     两者关键的不同是我们知道返回值的类型,对于泛型noOp,我们可以清楚的知道返回值的类型跟输入进来的值的类型相同。但都对于Any

    并不适合,它的返回值可以是任何类型。使用Any会逃避swift的类型系统。这样的话Any有各种各样的可能的运行时错误。

    在这里泛型和Any的区别我粗略的讲解了一下,下次我会另开一篇文章介绍两者的区别 

  • 相关阅读:
    API
    Object constructor
    function()
    For语句的衍生对象
    编程语言发展史
    将Paul替换成Ringo
    Document.write和 getElementById(ID)
    姓名,电话号码,邮箱的正则检测
    JavaScript-BOM与DOM
    管理心得
  • 原文地址:https://www.cnblogs.com/Ohero/p/4694608.html
Copyright © 2011-2022 走看看