Created
September 29, 2016 08:25
-
-
Save izmailoff/c2d7d56a8d097f682cd5eb6f895f9aa0 to your computer and use it in GitHub Desktop.
Take first n elements from scala list example - functional
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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