1

所需的最终打字稿代码是:

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)
}
4

1 回答 1

3

它是continuation monad,其中函数应用程序用作绑定操作

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

这是另一种编码,可以更容易地了解它是如何工作的。不是使用函数应用程序来绑定,而是使用显式bindunit函数。注意:这里的“bind”与monad二进制操作无关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

于 2018-09-01T05:33:25.047 回答