Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I'm not claiming that this answer is necessarily any better than <a href="https://stackoverflow.com/a/13963136/334519">drstevens's</a>, but it takes a slightly different approach and wouldn't fit in a comment there.</p> <p>First for our validation methods (note that I've changed the type of <code>toInt</code> a bit, for reasons I'll explain below):</p> <pre><code>import scalaz._, Scalaz._ def allDigits: (String) =&gt; ValidationNEL[String, String] = s =&gt; if (s.forall(_.isDigit)) s.successNel else "Not all digits".failNel def maxSizeOfTen: (String) =&gt; ValidationNEL[String, String] = s =&gt; if (s.size &lt;= 10) s.successNel else "Too big".failNel def toInt(s: String) = try(s.toInt.right) catch { case _: NumberFormatException =&gt; NonEmptyList("Still not an integer").left } </code></pre> <p>I'll define a type alias for the sake of convenience:</p> <pre><code>type ErrorsOr[+A] = NonEmptyList[String] \/ A </code></pre> <p>Now we've just got a couple of Kleisli arrows:</p> <pre><code>val validator = Kleisli[ErrorsOr, String, String]( allDigits.flatMap(x =&gt; maxSizeOfTen.map(x *&gt; _)) andThen (_.disjunction) ) val integerizer = Kleisli[ErrorsOr, String, Int](toInt) </code></pre> <p>Which we can compose:</p> <pre><code>val together = validator &gt;&gt;&gt; integerizer </code></pre> <p>And use like this:</p> <pre><code>scala&gt; together("aaa") res0: ErrorsOr[Int] = -\/(NonEmptyList(Not all digits)) scala&gt; together("12345678900") res1: ErrorsOr[Int] = -\/(NonEmptyList(Too big)) scala&gt; together("12345678900a") res2: ErrorsOr[Int] = -\/(NonEmptyList(Not all digits, Too big)) scala&gt; together("123456789") res3: ErrorsOr[Int] = \/-(123456789) </code></pre> <p>Using <code>flatMap</code> on something that isn't monadic makes me a little uncomfortable, and combining our two <code>ValidationNEL</code> methods into a Kleisli arrow in the <code>\/</code> monad—which also serves as an appropriate model for our string-to-integer conversion—feels a little cleaner to me.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload