函子03-AP IO

1.3k words

Ap函子

Ap(applicative)又叫应用函子。实现了ap方法。实现让不同的函子之间的相互调用。

🌰 Ap 核心实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Ap {
static of(value) {
return new this(value)
}

constructor(value) {
this.value = value
}

map(fn) {
return Ap.of(fn(this.value))
}

/** 接受函子,并将自身的 value 传入函子的map执行 */
ap(container) {
return container.map(this.value)
}
}

🌰 Ap 使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const num1 = Ap.of(2)
const num2 = Ap.of(3)
const add = (x, y) => x + y

// [object Object][object Object] 还得拆箱
console.log(add(num1, num2))

/** 多参数还使用柯里化 */
const addOne = (x) => {
return (y) => add(x, y)
}

// 使用ap方法
console.log(num1.map(addOne).ap(num2))

IO 函子

IO函子专门处理不纯的操作(脏操作), 所以其value为一个通用函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class IO {
static of(value) {
return new this(value)
}

constructor(value) {
this.value = value
}

/** 差异化 */
map(fn) {
// 因为 value 是一个函数,所以需要执行后返回给传入的fn
return IO.of(fn(this.value()))
}

isNothing() {
return this.value === null || this.value === undefined
}

join() {
return this.isNothing() ? MayBe.of(null) : this.value
}

chain(fn) {
return this.map(fn).join()
}
}

🍐 IO 使用

1
2
3
4
5
6
7
8
const fs = require('fs')

// readFileSync 返回一个IO函子,此时读取文件未执行(惰性)
const readFileSync = (file) => new IO(() => fs.readFileSync(file))

// 获取 01.txt 文件内容
const file = readFileSync('./01.txt').chain((out) => out.toString())
console.log(file)