scalawithcats / scala-with-cats

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

Adding solution with ensureOr to MonadError exercise #204

Open TonioGela opened 3 years ago

TonioGela commented 3 years ago

The exercise 4.5.4: Abstracting asks the reader to write a signature for the method

def validateAdult[F[_]](age: Int)(implicit me: MonadError[F, Throwable]): F[Int] = ???

The proposed solutions shows the usage of pure and raiseError and uses and if:

def validateAdult[F[_]](age: Int)(implicit me: MonadError[F, Throwable]): F[Int] =
  if(age >= 18) age.pure[F]
  else new IllegalArgumentException("Age must be greater than or equal to 18").raiseError[F, Int]

but since in the chapter the exercises refers to is specified that "Cats provides syntax for raiseError and handleErrorWith via cats.syntax.applicativeError and ensure via cats.syntax.monadError" it makes sense to me to show a solution that uses the ensure API like this:

def validateAdult[F[_]](age: Int)(implicit me: MonadError[F, Throwable]): F[Int] = 
  age.pure[F].ensure(new IllegalArgumentException("Age must be greater than or equal to 18"))(_ >= 18)

Plus, I personally love oneliners :P

TonioGela commented 9 months ago

@noelwelsh shall I close this PR? It hasn't been merged in years and it's probably outdated :)

noelwelsh commented 9 months ago

Please leave it open. I am working on the book, and intend to look at all the open PRs when I get to the relevant sections. I just can't afford to split my focus bouncing around different sections of the book given the limited time I have to work on it.

TonioGela commented 9 months ago

Please leave it open. I am working on the book, and intend to look at all the open PRs when I get to the relevant sections. I just can't afford to split my focus bouncing around different sections of the book given the limited time I have to work on it.

Thanks @noelwelsh! If you need some kind of help with the book in general just ask ;)

noelwelsh commented 9 months ago

The mailing list at https://www.scalawithcats.com/ is the best place to stay up-to-date. I post there when there is something to announce, and people can access the current draft. Should be posting there tomorrow.