24-Swift函數(shù)式編程

1.Array的常見操作

do {
    let arr = [1, 2, 3, 4]
    let arr2 = arr.map { $0 * 2 }
    // [2, 4, 6, 8]
    print(arr2)
    // [2, 4]
    let arr3 = arr.filter { $0 % 2 == 0 }
    // 10
    print(arr3)
    let arr4 = arr.reduce(0) { $0 + $1 }
    // 10
    print(arr4)
    let arr5 = arr.reduce(0, +)
    print(arr5)
}

do {
    func double(_ i: Int) -> Int { i * 2 }
    let arr = [1, 2, 3, 4]
    // [2, 4, 6, 8]
    print(arr.map(double))
}

do {
    let arr = [1, 2, 3]
    let arr2 = arr.map { Array.init(repeating: $0, count: $0) }
    // [[1], [2, 2], [3, 3, 3]]
    print(arr2)
    let arr3 = arr.flatMap { Array.init(repeating: $0, count: $0) }
    // [1, 2, 2, 3, 3, 3]
    print(arr3)
}

do {
    let arr = ["123", "test", "jack", "-30"]
    let arr2 = arr.map { Int($0) }
    // [Optional(123), nil, nil, Optional(-30)]
    print(arr2)
    let arr3 = arr.compactMap { Int($0) }
    // [123, -30]
    print(arr3)
}

do {
    // 使用reduce實(shí)現(xiàn)map、filter的功能
    let arr = [1, 2, 3, 4]
    // [2, 4, 6, 8]
    print(arr.map { $0 * 2 })
    print(arr.reduce([]) { $0 + [$1 * 2] })
    // [2, 4]
    print(arr.filter { $0 % 2 == 0 })
    print(arr.reduce([]) { $1 % 2 == 0 ? $0 + [$1] : $0 })
}

2.lazy的優(yōu)化

do {
    let arr = [1, 2, 3]
    let result = arr.lazy.map { (i: Int) -> Int in
        print("mapping \(i)")
        return i * 2
    }
    print("begin-----")
    print("mapped", result[0])
    print("mapped", result[1])
    print("mapped", result[2])
    print("end----")
    /*
     begin-----
     mapping 1
     mapped 2
     mapping 2
     mapped 4
     mapping 3
     mapped 6
     end----
     */
}

3.Optional的map和flatMap

do {
    let num1: Int? = 10
    let num2 = num1.map { $0 * 2 }
    // Optional(20)
    print(num2 as Any)
    
    let num3: Int? = nil
    let num4 = num3.flatMap { $0 * 2 }
    // nil
    print(num4 as Any)
}

do {
    /// 字符串 轉(zhuǎn) 日期
    let fmt = DateFormatter()
    fmt.dateFormat = "yyyy-MM-dd"
    let str: String? = "2011-09-10"
    // old
    let date1 = str != nil ? fmt.date(from: str!) : nil
    print(date1 as Any)
    // new
    let date2 = str.flatMap(fmt.date)
    print(date2 as Any)
}

do {
    let num1: Int? = 10
    let num2 = num1.map { Optional.some($0 * 2) }
    // Optional(Optional(20))
    print(num2 as Any)
    
    let num3 = num1.flatMap { Optional.some($0 * 2) }
    // Optional(20)
    print(num3 as Any)
}

do {
    let score: Int? = 98
    // old
    let str1 = score != nil ? "socre is \(score!)" : "No score"
    print(str1)
    // new
    let str2 = score.map { "score is \($0)" } ?? "No score"
    print(str2)
}

do {
    let num1: Int? = 10
    let num2 = (num1 != nil) ? (num1! + 10) : nil
    let num3 = num1.map { $0 + 10 }
    // num2、num3是等價(jià)的
    print(num2 as Any)
    print(num3 as Any)
}

do {
    struct Person {
        var name: String
        var age: Int
    }
    var items = [
        Person(name: "jack", age: 20),
        Person(name: "rose", age: 21),
        Person(name: "kate", age: 22)
    ]
    // old
    func getPerson1(_ name: String) -> Person? {
        let index = items.firstIndex { $0.name == name }
        return index != nil ? items[index!] : nil
    }
    // new
    func getPerson2(_ name: String) -> Person? {
        return items.firstIndex { $0.name == name }.map { items[$0] }
    }
}

do {
    struct Person {
        var name: String
        var age: Int
        init?(_ json: [String : Any]) {
            guard let name = json["name"] as? String,
                let age = json["age"] as? Int else {
                return nil
            }
            self.name = name
            self.age = age
        }
    }
    let json: Dictionary? = ["name" : "Jack", "age" : 10] // old
    let p1 = json != nil ? Person(json!) : nil
    // new
    let p2 = json.flatMap(Person.init)
    
    print(p1 as Any)
    print(p2 as Any)
}

4.函數(shù)式編程(Funtional Programming)

  • 函數(shù)式編程(Funtional Programming,簡稱FP)是一種編程范式,也就是如何編寫程序的方法論
    • 主要思想:把計(jì)算過程盡量分解成一系列可復(fù)用函數(shù)的調(diào)用
    • 主要特征:函數(shù)是“第一等公民”
  • 函數(shù)與其他數(shù)據(jù)類型一樣的地位,可以賦值給其他變量,也可以作為函數(shù)參數(shù)、函數(shù)返回值
  • 函數(shù)式編程最早出現(xiàn)在LISP語言,絕大部分的現(xiàn)代編程語言也對(duì)函數(shù)式編程做了不同程度的支持,比如
    • Haskell、JavaScript、Python、Swift、Kotlin、Scala等
  • 函數(shù)式編程中幾個(gè)常用的概念
    • Higher-Order Function、Function Currying
    • Functor、Applicative Functor、Monad
4.1.FP實(shí)踐 – 傳統(tǒng)寫法
// 假設(shè)要實(shí)現(xiàn)以下功能:[(num + 3) * 5 - 1] % 10 / 2
do {
    let num = 1
    func add(_ v1: Int, _ v2: Int) -> Int {
        v1 + v2
    }
    func sub(_ v1: Int, _ v2: Int) -> Int {
        v1 - v2
    }
    func multiple(_ v1: Int, _ v2: Int) -> Int {
        v1 * v2
    }
    func divide(_ v1: Int, _ v2: Int) -> Int {
        v1 / v2
    }
    func mod(_ v1: Int, _ v2: Int) -> Int {
        v1 % v2
    }
    divide(mod(sub(multiple(add(num, 3), 5), 1), 10), 2)
}

infix operator >>> : AdditionPrecedence
func >>><A, B, C>(_ f1: @escaping (A) -> B,_ f2: @escaping (B) -> C) -> (A) -> C {
    { f2(f1($0)) }
}

// FP實(shí)踐 – 函數(shù)式寫法
do {
    let num = 1
    func add(_ v: Int) -> (Int) -> Int {
        { $0 + v }
    }
    func sub(_ v: Int) -> (Int) -> Int {
        { $0 - v }
    }
    func multiple(_ v: Int) -> (Int) -> Int {
        { $0 * v }
    }
    func divide(_ v: Int) -> (Int) -> Int {
        { $0 / v }
    }
    func mod(_ v: Int) -> (Int) -> Int {
        { $0 % v }
    }
    let fn = add(3) >>> multiple(5) >>> sub(1) >>> mod(10) >>> divide(2)
    fn(num)
}
4.3高階函數(shù)(Higher-Order Function)

高階函數(shù)是至少滿足下列一個(gè)條件的函數(shù):

  • 接受一個(gè)或多個(gè)函數(shù)作為輸入(map、filter、reduce等)
  • 返回一個(gè)函數(shù)
  • FP中到處都是高階函數(shù)
do {
    func add(_ v: Int) -> (Int) -> Int { { $0 + v } }
}

4.4柯里化(Currying)

  • 什么是柯里化?
    • 將一個(gè)接受多參數(shù)的函數(shù)變換為一系列只接受單個(gè)參數(shù)的函數(shù)


      image.png
    • Array、Optional的map方法接收的參數(shù)就是一個(gè)柯里化函數(shù)
//柯里化
do {
    func add1(_ v1: Int, _ v2: Int) -> Int { v1 + v2 }
    add1(10, 20)
    
    func add(_ v: Int) -> (Int) -> Int { { $0 + v } }
    add(10)(20)
}

func add3(_ v1: Int, _ v2: Int) -> Int { v1 + v2 }
func add4(_ v1: Int, _ v2: Int, _ v3: Int) -> Int { v1 + v2 + v3 }
func currying<A, B, C>(_ fn: @escaping (A, B) -> C) -> (B) -> (A) -> C {
    { b in { a in fn(a, b) } }
}
func currying1<A, B, C, D>(_ fn: @escaping (A, B, C) -> D) -> (C) -> (B) -> (A) -> D {
    {   c in
        {   b in
            { a in
                fn(a, b, c)
            }
        }
    }
}
let curriedAdd1 = currying(add3)
print(curriedAdd1(10)(20))
let curriedAdd2 = currying1(add4)
print(curriedAdd2(10)(20)(30))

prefix func ~<A, B, C>(_ fn: @escaping (A, B) -> C) -> (B) -> (A) -> C {
    { b in { a in fn(a, b) } }
}

func add0(_ v1: Int, _ v2: Int) -> Int {
    v1 + v2
}
func sub0(_ v1: Int, _ v2: Int) -> Int {
    v1 - v2
}
func multiple0(_ v1: Int, _ v2: Int) -> Int {
    v1 * v2
}
func divide0(_ v1: Int, _ v2: Int) -> Int {
    v1 / v2
}
func mod0(_ v1: Int, _ v2: Int) -> Int {
    v1 % v2
}

let num = 1
let fn0 = (~add0)(3) >>> (~multiple0)(5) >>> (~sub0)(1) >>> (~mod0)(10) >>> (~divide0)(2)
fn0(num)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容