高阶函数的定义、使用与语义

<高阶函数定义了高阶类型的处理(映射)、低阶函数处理了低阶类型的映射,高阶函数依赖于低阶函数>

高阶函数的特点:

1、定义的高阶函数本身的实现 ;

2、定义了参量函数的接口:输入、输出;

3、定义了高阶函数的功能部分对输入函数的引用或使用方式。

 语义:定义高阶函数并声明混入函数的接口

本质是暴露低阶函数的接口给高阶函数使用;

scala:

def operate(f:(Int,Int) => Int ) = {

f(4,4)

swift:

protocol ViewChainable {}

extension ViewChainable where Self: UIView {

    @discardableResult

    func config(_ config: (Self) -> Void) -> Self {

        config(self)

        return self

    }

}

extension UIView: ViewChainable {

    func adhere(toSuperView: UIView) -> Self {

        toSuperView.addSubview(self)

        return self

    }

    @discardableResult

    func layout(snapKitMaker: (ConstraintMaker) -> Void) -> Self {

        self.snp.makeConstraints { (make) in

            snapKitMaker(make)

        }

        return self

    }

混入函数的混入形式(匿名函数):

语意:

调用高阶函数,同时定义符合接口声明的混入函数并传递进去

swift:

let label = UILabel()

    .adhere(toSuperView: view)

    .layout { (make) in

        make.top.equalToSuperview().offset(80)

        make.centerX.equalToSuperview()

    }

    .config { (label) in

        label.backgroundColor = UIColor.clear

        label.font = UIFont.systemFont(ofSize: 20)

        label.textColor = UIColor.darkGray

        label.text = "Label"

    }

extension PrimitiveSequence where TraitType == SingleTrait, ElementType == Response

{

    public func mapModel<T: HandyJSON>(_ type: T.Type) -> Single<Any> {

        return flatMap { response -> Single<Any> in

            return Single.just(response.mapModel(type))

        }

    }

    

    public func updateModel<T: HandyJSON>(_ model: T) -> Single<Any> {

        return flatMap { response -> Single<Any> in

            return Single.just(response.updateModel(model))

        }

    }

}

scala:

 //list元素乘以2,对每一个元素都做同一个操作

  val l =List(1,2,3,4,5,6,7,8)

  l.map((x:Int) => x*2)//最古老的方法

  l.map(x => x*2)//简化的写法

  l.map(_*2)//超简化写法

猜你喜欢

转载自www.cnblogs.com/feng9exe/p/10509723.html