所需的最终打字稿代码为:
transform(input)(transformation1)(transformation2)(...
// input is any data, e.g. string or object
// transformationX should be a transforming function
到目前为止,我已经在下面编写了代码,感觉就像我在发明轮子,也就是说,这种东西必须已经在FP中实现,但是我不知道它是怎么被调用的。谁能告诉您可以使用https://gcanti.github.io/fp-ts/中的哪个工具代替?
type Transformer = (transformation: Transformation) => Transformer
type Transformation = (input: object) => Transformer
const TranformerCreator = (input: object): Transformer
=> (transformation: Transformation): Transformer
=> transformation(input)
const transform: Transformation = (input: object) => {
return TranformerCreator(input)
}
const transformation1: Transformation = (input: object) => {
// do sometging with input
return TranformerCreator(input)
}
答案 0 :(得分:2)
这是continuation monad,其中函数应用程序用作 bind 操作
const cont = x =>
k => k (x)
const add1 = x =>
cont (x + 1)
const double = x =>
cont (x * 2)
const square = x =>
cont (x * x)
cont (2) (add1) (double) (square) (console.log)
// 36
// 2 -> add1 -> 3 -> double -> 6 -> square -> 36
这是另一种编码,可以使查看它的工作方式更加容易。代替使用函数应用程序进行绑定,使用显式bind
和unit
函数。注意:此处的“绑定”与Function.prototype.bind
无关,是指monad二进制操作
class Cont
{ constructor (run)
{ this.run = run
}
bind (f)
{ return new Cont (k => this.run (x => f (x) .run (k)))
}
static unit (x)
{ return new Cont (k => k (x))
}
}
const add1 = x =>
Cont.unit (x + 1)
const double = x =>
Cont.unit (x * 2)
const square = x =>
Cont.unit (x * x)
Cont.unit (2)
.bind (add1)
.bind (double)
.bind (square)
.run (console.log) // 36