Created
July 31, 2017 20:09
-
-
Save ramannanda9/1d6f27ec261b49ebb0eca43f47527df7 to your computer and use it in GitHub Desktop.
Filter with Tail Recursion
This file contains 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 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