0

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?

Marcelo Lazaroni
  • 9,819
  • 3
  • 35
  • 41

1 Answers1

1

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)))
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • Nice. But if one of the functions returns `Nothing` the entire result would be `Nothing`. I would like to ignore all `Nothing`s. – Marcelo Lazaroni Dec 15 '16 at 18:38
  • What do you mean, ignore? What else could you return if not `Nothing`? Please provide some example functions with example input and the expected output in your question. – Bergi Dec 15 '16 at 18:43
  • Imagine I have the string `"Name: John | Address: Apple Street"`. In this example, `getName` would return `Just "John"`, getAddress would return `Just "Apple Street"` and getPhone would return `Nothing`. My goal is to run all of these functions against the original string and concatenate the results, ignoring the `Nothing`s. In the example I gave, the desired output would be `"John, Apple Street"`. Is there a concise way to do that? – Marcelo Lazaroni Dec 18 '16 at 20:58
  • Please put that example in your question, I'll post another answer. – Bergi Dec 18 '16 at 21:53