Skip to content

Instantly share code, notes, and snippets.

@ryoppy
Created December 6, 2013 14:14
Show Gist options
  • Save ryoppy/7824609 to your computer and use it in GitHub Desktop.
Save ryoppy/7824609 to your computer and use it in GitHub Desktop.
練習用にコレクションメソッドの実装
// map(Seq(1,2,3)) { i => i + "?" } = Seq(1?, 2?, 3?)
def map[A, B](l: Seq[A])(f: (A) => B): Seq[B] = l match {
case h :: t => f(h) +: map(t)(f)
case _ => Nil
}
// find(Seq(1,2,3)) { i => i == 2 } = Some(2)
def find[T](l: Seq[T])(f: (T) => Boolean): Option[T] = l match {
case h :: t => if (f(h)) Option(h) else find(t)(f)
case _ => None
}
// reverse(Seq(1,2,3)) = Seq(3, 2, 1)
def reverse[T](l: Seq[T]): Seq[T] = l match {
case h :: t => reverse(t) :+ h
case _ => l
}
// foldLeft(Seq(1,2,3))(0) { (n: Int, i: Int) => n + i } = 6
def foldLeft[A, B](l: Seq[A])(n: B)(f: (B, A) => B): B = l match {
case h :: t => foldLeft(t)(f(n, h))(f)
case _ => n
}
// scan(Seq(1,2,3))(0) { (n, i) => i + n } = Seq(1, 3, 6)
def scan[A, B](l: Seq[A])(n: B)(f: (B, A) => B): Seq[B] = l match {
case h :: t => f(n, h) +: scan(t)(f(n, h))(f)
case _ => Nil
}
// zip(Seq(1,2,3), Seq(7,8,9)) = Seq((1,7), (2,8), (3,9))
def zip[T](l1: Seq[T], l2: Seq[T]): Seq[(T, T)] = (l1, l2) match {
case (h1 :: t1, h2 :: t2) => (h1, h2) +: zip(t1, t2)
case _ => Nil
}
// unzip(Seq((1,2), (3,4)) = (Seq(1, 3),Seq(2, 4))
def unzip[T](l: Seq[(T, T)]): (Seq[T], Seq[T]) = l match {
case (a, b) :: t => unzip(t) match { case (aa, bb) => (a +: aa, b +: bb) }
case _ => (Nil, Nil)
}
// zipWithIndex(Seq("a", "b", "c") = Seq((a,0), (b,1), (c,2))
def zipWithIndex[T](l: Seq[T], i: Int = 0): Seq[(T, Int)] = l match {
case h :: t => (h, i) +: zipWithIndex(t, i + 1)
case _ => Nil
}
// forall(Seq(1,2,3)) { i => i == 1 } = false
// forall(Seq(1,2,3)) { i => i == 1 || i == 2 || i == 3 } = true
def forall[T](l: Seq[T])(f: (T) => Boolean): Boolean = l match {
case h :: t => f(h) && forall(t)(f)
case _ => true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment