函数式编程思想-计算器-Calculate
2016-08-14 本文已影响128人
solozyx
1.一般编程
Calculate.h
#import <Foundation/Foundation.h>
@interface Calculate : NSObject
@property (nonatomic,assign) int result;
- (instancetype)add:(int)num;
@end
Calculate.m
#import "Calculate.h"
@implementation Calculate
- (instancetype)add:(int)num{
_result += num;
return self;
}
@end
ViewController.m
#import "ViewController.h"
#import "Calculate.h"
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
Calculate *calculate = [Calculate new];
int result = [[[[[[[calculate add:1] add:2] add:3] add:4] add:5] add:6] result];
NSLog(@"result = %d",result);
// 2016-08-14 17:15:13.444 Calculate[19636:1580250] result = 21
}
@end
2.函数式编程思想
函数式编程思想
:把操作尽量写成一系列嵌套的函数或方法调用
函数式编程特点
:方法必须返回本身对象,参数是block,该block的参数是需要操作的值,该block的返回值是操作的结果
Calculate.h
#import <Foundation/Foundation.h>
@interface Calculate : NSObject
@property (nonatomic,assign) int result;
- (instancetype)add:(int (^) (int result))block;
@end
Calculate.m
#import "Calculate.h"
@implementation Calculate
- (instancetype)add:(int (^) (int result))block{
_result = block(_result);
return self;
}
@end
ViewController.m
- (void)viewDidLoad{
[super viewDidLoad];
Calculate *calculate = [Calculate new];
int result = [[calculate add:^int(int result) {
result += 1;
result += 2;
result += 3;
result += 4;
result += 5;
return result;
}] result];
NSLog(@"result = %d",result);
// 2016-08-14 17:32:15.356 Calculate[21322:1595078] result = 15
}
3.函数化更进一层
Calculate.h
#import <Foundation/Foundation.h>
@interface Calculate : NSObject
@property (nonatomic,assign) int result;
@property (nonatomic,assign) BOOL isEqual;
- (instancetype)add:(int (^) (int result))block;
- (instancetype)equal:(BOOL (^) (int result))block;
@end
Calculate.m
#import "Calculate.h"
@implementation Calculate
- (instancetype)add:(int (^) (int result))block{
_result = block(_result);
return self;
}
-(instancetype)equal:(BOOL (^)(int))block{
_isEqual = block(_result);
return self;
}
@end
ViewController.m
#import "ViewController.h"
#import "Calculate.h"
@implementation ViewController
- (void)viewDidLoad{
[super viewDidLoad];
Calculate *calculate = [Calculate new];
BOOL isEqual = [[[calculate add:^int(int result) {
result += 1;
result += 2;
result += 3;
result += 4;
result += 5;
return result;
}] equal:^BOOL(int result) {
return (result == 15);
}] isEqual];
NSLog(@"isEqual = %d",isEqual);
// 2016-08-14 17:47:29.657 Calculate[22823:1608283] isEqual = 1
}
@end