scalaの練習問題やってみた
プログラミング言語 Scala Wiki - Scala練習問題
// x + y ただし「+」を使わない def add(x: Int, y: Int): Int = y match { case 0 => x case _ => add(succ(x), pred(y)) } // リストの合計 def sum(x: List[Int]): Int = x match { case x :: xs => add(x, sum(xs)) case Nil => 0 } // リストの長さ def length[A](x: List[A]): Int = x match { case x :: xs => 1 + length(xs) case Nil => 0 } // リストの要素全部に関数を適用したリストを返す def map[A, B](x: List[A], f: A => B): List[B] = x match { case x :: xs => f(x) :: map(xs, f) case Nil => Nil } // リストから条件に当てはまるものだけ抜き出す def filter[A](x: List[A], f: A => Boolean): List[A] = x match { case x :: xs => if(f(x)) x :: filter(xs, f) else filter(xs, f) case Nil => Nil } // リストとリストをガッチャンコする def append[A](x: List[A], y: List[A]): List[A] = x match { case x :: xs => x :: append(xs, y) case Nil => y } // リストの中のリストを全部ガッチャンコする def concat[A](x: List[List[A]]): List[A] = x match { case x :: xs => append(x, concat(xs)) case Nil => Nil } // リストの要素全部に関数を適用して全部ガッチャンコする def concatMap[A, B](x: List[A], f: A => List[B]): List[B] = concat(map(x, f)) // 一番でかいものを返す def maximum(x: List[Int]): Int = x match { case x :: Nil => x case x :: y :: xs if(x > y) => maximum(x :: xs) case x :: y :: xs => maximum(y :: xs) case Nil => throw new IllegalArgumentException } // リストを逆順にする def reverse[A](x: List[A]): List[A] = x match { case x :: xs => append(reverse(xs), x :: Nil) case Nil => Nil }
難しかったー><
maximumだけどうしても分からなかったのでカンニングしてしまいました。
OCaml vs. Scala パターンマッチ:Rainy Day Codings:So-net blog
↑のページ「ガード条件」のところ