Skip to content

Instantly share code, notes, and snippets.

@purukaushik
Created February 11, 2017 08:13
Show Gist options
  • Save purukaushik/b5b1daee58788cb7958e14a523786752 to your computer and use it in GitHub Desktop.
Save purukaushik/b5b1daee58788cb7958e14a523786752 to your computer and use it in GitHub Desktop.
Functional building blocks- map, filter, reduce etc ab initio in scala
object AbInitio {
def map[T,U](f : T => U, xs: List[T]): List[U] ={
def helper(acc: List[U], xs1: List[T]):List[U] = {
if(xs1.isEmpty) acc
else helper(acc :+ f(xs1.head), xs1.tail)
}
helper(List[U](), xs)
}
def filter[T](f: T => Boolean, xs: List[T]):List[T] = {
def helper(acc: List[T], xs1: List[T]): List[T] = {
if(xs1.isEmpty) acc
else if(f(xs1.head)) helper(acc :+ xs1.head, xs1.tail)
else helper(acc, xs1.tail)
}
helper(List[T](), xs)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment