読者です 読者をやめる 読者になる 読者になる

はわわーっ

はわわわわっ

scalaでリスト処理とか

リストを処理する関数を作ってみる。

scala> val intlist = List.range(0,10)
intlist: List[Int] = List(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)

scala> val strlist = List("abc", "def", "xyz", "uvw")
strlist: List[String] = List(abc, def, xyz, uvw)

scala> def head[A](xs: List[A]): A = xs match {
     |   case Nil => sys.error("empty")
     |   case x :: xs => x
     | }
head: [A](xs: List[A])A

scala> head(intlist)
res0: Int = 0

scala> head(strlist)
res1: String = abc

scala> def tail[A](xs: List[A]): A = xs match {
     |   case Nil => sys.error("empty")
     |   case x :: Nil => x
     |   case x :: xs => tail(xs)
     | }
tail: [A](xs: List[A])A

scala> tail(intlist)
res2: Int = 9

scala> tail(strlist)
res3: String = uvw

scala> def maximum[A](xs: List[A])(implicit cmp: Ordering[A]): A = xs match {
     |   case Nil => sys.error("empty")
     |   case x :: Nil => x
     |   case x :: xs => cmp.max(x, maximum(xs))
     | }
maximum: [A](xs: List[A])(implicit cmp: Ordering[A])A

scala> maximum(intlist)
res4: Int = 9

scala> maximum(strlist)
res6: String = xyz

scala> def replicate[A](n: Int, x: A): List[A] = {
     |   if (n <= 0) Nil
     |   else x :: replicate(n - 1, x)
     | }
replicate: [A](n: Int, x: A)List[A]

scala> replicate(3, 5)
res7: List[Int] = List(5, 5, 5)

scala> def take[A](n: Int, xs: List[A]): List[A] = (n, xs) match {
     |   case (n, _) if n <= 0 => Nil
     |   case (_, Nil) => Nil
     |   case (n, x :: xs) => x :: take(n - 1, xs)
     | }
take: [A](n: Int, xs: List[A])List[A]

scala> take(3, List.range(10, 0, -2))
res8: List[Int] = List(10, 8, 6)

scala> def zip[A, B](xs: List[A], ys: List[B]): List[(A, B)] =
     |   (xs, ys) match {
     |     case (_, Nil) => Nil
     |     case (Nil, _) => Nil
     |     case (x :: xs, y :: ys) => (x, y) :: zip(xs, ys)
     |   }
zip: [A, B](xs: List[A], ys: List[B])List[(A, B)]

scala> zip(List("aaa", "bbb", "ccc"), List.range(0,10))
res9: List[(String, Int)] = List((aaa,0), (bbb,1), (ccc,2))

こんな感じ。
比較するときは Ordering[A] を使うらしい。
あと、パターンマッチすげー。