简体   繁体   中英

Apply list of functions to maybe value in Javascript

I'm using ramda-fantasy for the monads. I have a string inside a maybe and a some functions that will perform regex matches on a string and return a Maybe String .

How do I map the maybe to apply all of the functions and concatenate the result?

I have

const fieldRetrievers = [ 
  getAddress,
  getName,
  getPhone, 
]

const text = Maybe.of("a text")

// I want to define
// List (String -> Maybe String) -> Maybe String -> Maybe String
function getInfo(retrievers, maybeText) {...}

How can I do that?

You're looking for composeK , the function composition over monadic structures ("kleisli arrows").

Basically, your resulting function is supposed to repeatedly chain onto the input:

text.chain(getAddress).chain(getName).chain(getPhone)

which you could implement using a reduce over your array of functions:

R.reduce((m, f) => m.chain(f), text, fieldRetrievers)

so you'd write

const getInfo = R.flip(R.reduce(R.flip(R.chain)))

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