Skip to content

Instantly share code, notes, and snippets.

@izmailoff
Created September 29, 2016 08:25
Show Gist options
  • Save izmailoff/c2d7d56a8d097f682cd5eb6f895f9aa0 to your computer and use it in GitHub Desktop.
Save izmailoff/c2d7d56a8d097f682cd5eb6f895f9aa0 to your computer and use it in GitHub Desktop.
Take first n elements from scala list example - functional
def take[A](xs: List[A], n: Int): List[A] = {
def loop(xy: List[A], rem: Int, accu: List[A]): List[A] =
if(rem <= 0) accu
else xy match {
case h :: t => loop(t, rem - 1, accu ::: List(h))
case _ => accu
}
loop(xs, n, Nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment