Last active
May 21, 2016 06:34
-
-
Save balajisivaraman/d08475fd8e913a7e9abb1616224164cd to your computer and use it in GitHub Desktop.
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
sealed trait List[+T] | |
case object Nil extends List[Nothing] | |
case class Cons[+T](head: T, tail: List[T]) extends List[T] | |
object List { | |
def head[T](list: List[T]): T = list match { | |
case Nil => throw new RuntimeException("Empty List") | |
case Cons(x, _) => x | |
} | |
def tail[T](list: List[T]): List[T] = list match { | |
case Nil => Nil | |
case Cons(_, xs) => xs | |
} | |
def map[T, U](list: List[T])(f: T => U): List[U] = list match { | |
case Nil => Nil | |
case Cons(x, xs) => Cons(f(x), map(xs)(f)) | |
} | |
def fold[T, U](list: List[T])(default: U)(f: (T, U) => U): U = | |
list match { | |
case Nil => default | |
case Cons(x, xs) => f(x, fold(xs)(default)(f)) | |
} | |
} | |
List.head(Cons(1, Cons(2, Nil))) | |
List.map(Cons(1, Cons(2, Nil)))(x => x * x) | |
List.fold(Cons(1, Cons(2, Nil)))(0)((x,y) => x + y) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment