Skip to content

Instantly share code, notes, and snippets.

@rkrzewski
Last active August 29, 2015 13:59
Show Gist options
  • Select an option

  • Save rkrzewski/10901806 to your computer and use it in GitHub Desktop.

Select an option

Save rkrzewski/10901806 to your computer and use it in GitHub Desktop.
def drop[T](n: Int, ts: Seq[T]): Seq[T] = {
@tailrec
def go(i: Int, ts: Seq[T], acc: Seq[T]): Seq[T] = (i, ts) match {
case (`n`, _ +: t) => go(0, t, acc)
case (_, h +: t) => go(i + 1, t, h +: acc)
case _ => acc.reverse
}
go(0, ts, Seq())
}
def drop[T](n: Int, ts: Seq[T]): Seq[T] = {
@tailrec
def go(i: Int, ts: Seq[T], acc: Seq[T]): Seq[T] = (i, ts) match {
case (i, _ +: t) if (i == n) => go(0, t, acc)
case (_, h +: t) => go(i + 1, t, h +: acc)
case _ => acc.reverse
}
go(0, ts, Seq())
}
def takeWhile[T](ts: Seq[T])(p: T => Boolean): Seq[T] = {
@tailrec
def go(ts: Seq[T], acc: Seq[T]): Seq[T] = ts match {
case h +: t if p(h) => go(t, h +: acc)
case _ => acc.reverse
}
go(ts, Seq())
}
def isPalindrome1[T](ts: Seq[T]): Boolean =
ts == ts.reverse
def isPalindrome[T](ts: Seq[T]): Boolean =
ts.zip(ts.reverse) forall { case (a, b) => a == b }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment