简体   繁体   中英

What is the name of the wheel from FP, that I am trying to invent? (see the code)

The desired final typescript code is:

transform(input)(transformation1)(transformation2)(...
// input is any data, e.g. string or object
// transformationX should be a transforming function

I've wrote the code below so far, and I feel like I am inventing the wheel, ie something like this must be already implemented in FP, but I don't know how it is called. Can anyone tell which tool from https://gcanti.github.io/fp-ts/ can be used instead?

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

It's the continuation monad , where function application is used as the bind operation

 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 

Here's another encoding that may make it easier to see how it works. Instead of using function application to bind, explicit bind and unit functions are used. Note: "bind" here is unrelated to Function.prototype.bind and refers to the monad binary operation

 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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM