Home 函数式编程
Post
Cancel

函数式编程

函数式编程:把每个操作都写作一连串的函数或者方法,使代码高度聚合,便于管理。正因为每次都可以调用自己的方法,所以每次都返回自己。

例子:设计一个计算器Calulator:

Calulator属性和方法:

1
2
3
4
5
6
7
8
9
10
11
@interface Calulator : NSObject

@property (nonatomic, assign) BOOL isEqule;//是否等于
@property (nonatomic, assign) int result;//每次计算的结果

//每次都返回自己
- (Calulator *)caculator:(int (^)(int result))calulator;
//每次都返回自己
- (Calulator *)equle:(BOOL (^)(int result))operation;

@end

实现方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@implementation Calulator

- (Calulator *)caculator:(int (^)(int))calulator{
    
    _result += calulator(_result);
    
    return self;
}

- (Calulator *)equle:(BOOL (^)(int))operation{
    
    _isEqule = operation(_result);
    
    return self;
}

@end

用法:

计算 8 * 2 是否等于 16

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
// 8 * 2 == 16

Calulator * c = [[Calulator alloc]init];

// 计算 8 * 2 判断是否等于16

BOOL isEqule = [[[c caculator:^int(int result) {//计算8 * 2
    
    result += 8;
    result *= 2;
    return result;
    
}] equle:^BOOL(int result) {//计算结果是否为16
    
    return  result == 16;
    
}] isEqule];//最后获取该bool值

NSLog(@"%d",isEqule);

打印结果1,即等于:

函数式编程让代码高度聚合,就是这么炫酷这么装逼!

This post is licensed under CC BY 4.0 by the author.

如何获取某一坐标的静态地图(静态图片)?

合并UIImage