[Scala] Solution for nested match statements (for practice)

practice about https://gist.github.com/2382341.

// see https://gist.github.com/2382341

// scalaz for only solution3
import scalaz._
import Scalaz._

object SolutionForMultiNestedMatchforMyStudy {

  def f(num: Int): Option[Int] = {
    num match {
      case 0 => Some(1)
      case 1 => Some(2)
      case 2 => Some(3)
      case _ => None
    }
  }

  def solution1(num: Int): Int = {
    f(num) match {
      case Some(v1) => {
        f(v1) match {
          case Some(v2) => {
            f(v2) match {
              case Some(v3) => v3
              case _ => -3
            }
          }
          case _ => -2
        }
      }
      case _ => -1
    }
  }

  def solution2(num: Int): Int = {
    val v1 = f(num)
    val v2 = v1.flatMap(f)
    val v3 = v2.flatMap(f)

    (v1, v2, v3) match {
      case (Some(_), Some(_), Some(result)) => result
      case (Some(_), Some(_), None) => -3
      case (Some(_), None, None) => -2
      case _ => -1
    }
  }

  def solution3(num: Int): Int = {
    f(num).toSuccess(-1).flatMap(f(_).toSuccess(-2)).flatMap(f(_).toSuccess(-3)).fold(identity, a => a)
  }

  def solution4(num: Int): Int = {
    (for {
      v1 <- f(num).toRight(-1).right
      v2 <- f(v1).toRight(-2).right
      v3 <- f(v2).toRight(-3).right
    } yield v3).merge
  }

  def solution5(num: Int): Int = {
    val v1 = f(num).getOrElse { return -1 }
    val v2 = f(v1).getOrElse { return -2 }
    f(v2).getOrElse { return -3 }
  }

  def example {
    (0 to 3).foreach{n => println(solution1(n))}
    println
    
    (0 to 3).foreach{n => println(solution2(n))}
    println
    
    (0 to 3).foreach{n => println(solution3(n))}
    println
    
    (0 to 3).foreach{n => println(solution4(n))}
    println
    
    (0 to 3).foreach{n => println(solution5(n))}
  }
}

One thought on “[Scala] Solution for nested match statements (for practice)

Leave a Reply