25-函数式编程

2023-05-11  本文已影响0人  二斤寂寞

Array的常见操作

var arr = [1, 2, 3, 4]
// [2, 4, 6, 8]
var arr2 = arr.map { $0 * 2 }
// [2, 4]
var arr3 = arr.filter { $0 % 2 == 0 } 
// 10
var arr4 = arr.reduce(0) { $0 + $1 } 
// 10
var arr5 = arr.reduce(0, +) 
func double(_ i: Int) -> Int { i * 2 } 
var arr = [1, 2, 3, 4]
// [2, 4, 6, 8] 
print(arr.map(double)) 
var arr = [1, 2, 3]
// [[1], [2, 2], [3, 3, 3]]
var arr2 = arr.map { Array.init(repeating: $0, count: $0) }
// [1, 2, 2, 3, 3, 3]
var arr3 = arr.flatMap { Array.init(repeating: $0, count: $0) } 
var arr = ["123", "test", "jack", "-30"] 
// [Optional(123), nil, nil, Optional(-30)] 
var arr2 = arr.map { Int($0) }
// [123, -30]
var arr3 = arr.compactMap { Int($0) } 
// 使用reduce实现map、filter的功能 
var 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 })

lazy的优化

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

Optional的map和flatMap

var num1: Int? = 10
// Optional(20)
var num2 = num1.map { $0 * 2 } 

var num3: Int? = nil
// nil
var num4 = num3.map { $0 * 2 } 
var num1: Int? = 10
// Optional(Optional(20))
var num2 = num1.map { Optional.some($0 * 2) }
// Optional(20)
var num3 = num1.flatMap { Optional.some($0 * 2) } 
var num1: Int? = 10
var num2 = (num1 != nil) ? (num1! + 10) : nil 
var num3 = num1.map { $0 + 10 }
// num2、num3是等价的                               
var fmt = DateFormatter()
fmt.dateFormat = "yyyy-MM-dd"
var str: String? = "2011-09-10"
// old
var date1 = str != nil ? fmt.date(from: str!) : nil // new
var date2 = str.flatMap(fmt.date) 
var score: Int? = 98
// old
var str1 = score != nil ? "socre is \(score!)" : "No score" 
// new
var str2 = score.map { "score is \($0)" } ?? "No score"   

Optional的map和flatMap

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

Optional的map和flatMap

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

var json: Dictionary? = ["name" : "Jack", "age" : 10] 
// old
var p1 = json != nil ? Person(json!) : nil
// new                                                  
var p2 = json.flatMap(Person.init) 

函数式编程(Funtional Programming)

FP 实践 – 传统写法

// 假设要实现以下功能:[(num + 3) * 5 - 1] % 10 / 2 
var 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)

FP 实践 – 函数式写法

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

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

var fn = add(3) >>> multiple(5) >>> sub(1) >>> mod(10) >>> divide(2)
fn(num)

高阶函数(Higher-Order Function)

func add(_ v: Int) -> (Int) -> Int { { $0 + v } } 

柯里化(Currying)

image.png

柯里化(Currying)

func add1(_ v1: Int, _ v2: Int) -> Int { v1 + v2 }
func add2(_ 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 currying<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(add1)
print(curriedAdd1(10)(20))
let curriedAdd2 = currying(add2)
print(curriedAdd2(10)(20)(30))

柯里化(Currying)

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 }

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

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

var num = 1
var fn = (~add)(3) >>> (~multiple)(5) >>> (~sub)(1) >>> (~mod)(10) >>> (~divide)(2)
fn(num)

函子(Functor)

// Array<Element> 
public func map<T>(_ transform: (Element) -> T) -> Array<T>

// Optional<Wrapped>
public func map<U>(_ transform: (Wrapped) -> U) -> Optional<U>

函子(Functor)

image.png

适用函子(Applicative Functor)

func pure<A>(_ value: A) -> F<A>                                                  
func <*><A, B>(fn: F<(A) -> B>, value: F<A>) -> F<B> 
func pure<A>(_ value: A) -> A? { value }
infix operator <*> : AdditionPrecedence
func <*><A, B>(fn: ((A) -> B)?, value: A?) -> B? {
   guard let f = fn, let v = value else { return nil }                                            
   return f(v) 
} 

var value: Int? = 10
var fn: ((Int) -> Int)? = { $0 * 2}
// Optional(20)
print(fn <*> value as Any)
image.png

适用函子(Applicative Functor)

func pure<A>(_ value: A) -> [A] { [value] }
func <*><A, B>(fn: [(A) -> B], value: [A]) -> [B] { 
    var arr: [B] = []
    if fn.count == value.count {                                                 
        for i in fn.startIndex..<fn.endIndex {
            arr.append(fn[i](value[i]))          
        } 
    }                                             
    return arr 
} 

// [10] 
print(pure(10))

var arr = [{ $0 * 2}, { $0 + 10 }, { $0 - 5 }] <*> [1, 2, 3] 
// [2, 12, -2]
print(arr) 

单子(Monad)

func pure<A>(_ value: A) -> F<A>                                                  
func flatMap<A, B>(_ value: F<A>, _ fn: (A) -> F<B>) -> F<B> 
上一篇下一篇

猜你喜欢

热点阅读