[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))}
  }
}

Converting hex string and byte array by Scala fixed

Converting hex string to byte array, and byte array to hex string by Scala. Fixed to remove string except hex.

object HexBytesUtil {

  def hex2bytes(hex: String): Array[Byte] = {
    hex.replaceAll("[^0-9A-Fa-f]", "").sliding(2, 2).toArray.map(Integer.parseInt(_, 16).toByte)
  }

  def bytes2hex(bytes: Array[Byte], sep: Option[String] = None): String = {
    sep match {
      case None => bytes.map("%02x".format(_)).mkString
      case _ => bytes.map("%02x".format(_)).mkString(sep.get)
    }
    // bytes.foreach(println)
  }

  def example {
    val data = "48 65 6C 6C 6F 20 57 6F 72 6C 64 21 21"
    val bytes = hex2bytes(data)
    println(bytes2hex(bytes, Option(" ")))

    val data2 = "48-65-6C-6C-6F-20-57-6F-72-6C-64-21-21"
    val bytes2 = hex2bytes(data2)
    println(bytes2hex(bytes2, Option("-")))

    val data3 = "48656C6C6F20576F726C642121"
    val bytes3 = hex2bytes(data3)
    println(bytes2hex(bytes3))
  }

}

Converting hex string and byte array by Scala

Converting hex string to byte array, and byte array to hex string by Scala.