-1

I am having trouble with understanding how to convert this into a for-comprehension. Could someone please explain how this can be done?

    (parseCommand(x)
      .flatMap { c =>
        calculate(c).map(r => renderResult(c, r))
      })
      .left
      .map(e => e.value)
      .merge
    ```
  • 2
    You can't, at least not the whole expression. Not sure what `left` returns, but you can't mix that inside the `for` and then you may add another `for` for the next `map` but the final `merge` would also be outside. Anyways, the code would just look worse. - Why you want to transform it into a `for`? – Luis Miguel Mejía Suárez Sep 26 '21 at 18:18

2 Answers2

1

You haven't provided enough information to answer your question.

  • What type does parseCommand() return?
  • What type does calculate() return?
  • Why translate to a for comprehension? What's your goal?

Assuming that parseCommand() and calculate() return the same or compatible types, then the 1st map() and flatMap() can be translated like so:

(for {
       c <- parseCommand(x)
       r <- calculate(c)
     } yield renderResult(c, r)
).left
 .map(e => e.value)
 .merge
 ...

The 2nd map() can't be folded in to this for because there can be only one map() per for comprehension. You could, however, turn it into its own, nested, for comprehension, but remember that it makes no difference to the compiler, so the only real reason to use for is to enhance code readability, and nested fors seldom achieve that.

jwvh
  • 50,871
  • 7
  • 38
  • 64
-2

I managed to convert it like this:

(for {
      c <- parseCommand(x)
      r <- calculate(c)
    } yield renderResult(c, r)).left.map(x => x.value).merge
  }