scalawithcats / scala-with-cats

Source code for Scala with Cats
http://underscore.io/books/scala-with-cats
396 stars 133 forks source link

explaining Monadic for comprehension #124

Open phderome opened 6 years ago

phderome commented 6 years ago

Some less experienced readers who have never seen a for comprehension de-sugared will block at this first comment touching on the topic:

“Plus, if we have both flatMap and map we can use for comprehensions to clarify the sequencing behaviour:”

You de-sugar a few pages later on in context of Futures. I'd argue the de-sugaring should be shown at the very first opportunity such as this intro sentence that links flatMap and map with the Scala for comprehension.

nashid commented 6 years ago

This is definitely confusing. The code that follows is:

def stringDivideBy(aStr: String, bStr: String): Option[Int] = for {
    aNum <- parseInt(aStr)
    bNum <- parseInt(bStr)
    ans  <- divide(aNum, bNum)
} yield ans

If we de-sugar this code it will be like:

parseInt(aStr).flatMap { aNum =>
        parseInt(bStr).flatMap { bNum =>
          divide(aNum, bNum)
        }
      }

There is no need for map operation here. So overall this just makes thing convoluted. A rewording would be better.