Skip to content

Instantly share code, notes, and snippets.

@ramannanda9
Created July 31, 2017 20:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramannanda9/1d6f27ec261b49ebb0eca43f47527df7 to your computer and use it in GitHub Desktop.
Save ramannanda9/1d6f27ec261b49ebb0eca43f47527df7 to your computer and use it in GitHub Desktop.
Filter with Tail Recursion
def filter[K](list: List[K], f: K => Boolean): List[K] = {
@tailrec
def filterRec(list: List[K], f: K => Boolean): List[K] = list match {
case Nil => list
case list: List[K] => if (f(list.head)) filterRec(list.head :: list.tail, f) else filterRec(list.tail, f)
}
filterRec(list, f)
}
val listToFilter = 2 :: 5 :: Nil
listToFilter.filter(_ > 2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment