×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Scala
Posted by: osocron coder
Added: Sep 30, 2016 2:43 PM
Views: 11
A Monad that makes sure that the number of elements in your type is correct.
  1. trait ValidType[+A] {
  2.  
  3.   def map[B](f: A => B)(implicit n: Int,
  4.                         p: (B, Int) => Boolean): ValidType[B] = this match {
  5.     case LengthN(v) => LengthN(f(v))
  6.     case InvalidL => InvalidL
  7.   }
  8.  
  9.   def flatMap[B](f: A => ValidType[B])
  10.                 (implicit n: Int,
  11.                  p: (ValidType[B], Int) => Boolean): ValidType[B] =
  12.     map(f) getOrElse InvalidL
  13.  
  14.   def getOrElse[B >: A](default: => B)(implicit n: Int,
  15.                                        p: (B, Int) => Boolean): B = this match {
  16.     case LengthN(v) => v
  17.     case InvalidL => default
  18.   }
  19.  
  20. }
  21.  
  22. case object InvalidL extends ValidType[Nothing]
  23.  
  24. class LengthN[A](val v: A)
  25.                  (implicit val n: Int,
  26.                   val p: (A, Int) => Boolean) extends ValidType[A]
  27.  
  28. object LengthN {
  29.  
  30.   def apply[A](v: A)(implicit n: Int, p: (A, Int) => Boolean): ValidType[A] =
  31.     if (p(v, n)) new LengthN(v) else InvalidL
  32.  
  33.   def unapply[A](arg: LengthN[A]): Option[A] = Some(arg.v)
  34.  
  35. }