現実逃避的に書いたので

http://blog.tmorris.net/scala-exercises-for-beginners/
せっかくなので貼っておく。

object Exercise {
  def succ(n: Int) = n + 1
  def pred(n: Int) = n - 1
  def add(x:Int, y:Int) : Int =
    if ( x == 0 )
      y
    else
      add(pred(x), succ(y))
  def sum(xs: List[Int]) : Int =
    xs match {
      case List()      => 0
      case (x::xs) => x + sum(xs)
    }
  def length[A](xs: List[A]) : Int =
    xs match {
      case List() => 0
      case (_::xs) => 1 + length(xs)
    }
  def map[A, B](f:A=>B, xs:List[A]) : List[B] =
    xs match {
      case List()  => List()
      case (x::xs) => f(x) :: map(f, xs)
    }
  def filter[A](p:A => Boolean, xs: List[A]) : List[A] =
    xs match {
      case List() => List()
      case (x::xs) => if ( p(x) ) x :: filter(p, xs)
                      else        filter(p, xs)
    }
  def append[A](xs:List[A], ys:List[A]) : List[A] =
    xs match {
      case List()  => ys
      case (x::xs) => x :: append(xs,ys)
    }
  def concat[A](xss:List[List[A]]) : List[A] =
    xss match {
      case List()  => List()
      case (xs::xss) => append(xs, concat(xss))
    }
  def concatMap[A,B](f:A=>List[B], xs:List[A]) : List[B] =
    xs match {
      case List()  => List()
      case (x::xs) => append(f(x), concatMap(f, xs))
    }
  def maximum(xs:List[Int]) : Int = {
    def loop(cur:Int, xs:List[Int]) : Int =
      xs match {
        case List()  => cur
	case (x::xs) => if ( x > cur )
	     	     	  loop(x, xs)
			else
			  loop(cur, xs)
      }
    loop(0, xs)
  }
  def reverse[A](xs:List[A]) : List[A] = {
    def reverser(xs:List[A],result:List[A]) : List[A] =
      xs match {
        case List()  => result
	case (x::xs) => reverser(xs, x::result)
      }
    reverser(xs, List())
  }

  def main(args: Array[String]) {
    val l = List(1,3,5)
    println("3+5="+add(3,5).toString())
    println("sum(1,3,5)="+sum(l).toString())
    println("length(1,3,5)="+length(l).toString())
    println("map((x:Int)=>x+1, (1,3,5))="+map((x:Int)=>x+1, l).toString())
    println("filter((x:Int) => x < 3 ,(1,3,5))="+filter((x:Int) => x < 3, l))
    println("append((1,3,5),(1,3,5))="+append(l,l).toString())
    println("concat(((1,3,5),(1,3,5)))="+concat(List(l,l)))
    println("concatMap(x->[x,x+1])="+concatMap((x:Int) => List(x,x+1), l))
    println("maximum(1,3,5)="+maximum(l).toString())
    println("reverse(1,3,5)="+reverse(l).toString())
  }