Skip to content

Instantly share code, notes, and snippets.

@ShaneDelmore
Created December 5, 2015 23:36
Show Gist options
  • Save ShaneDelmore/b73d94b5a91edf338c34 to your computer and use it in GitHub Desktop.
Save ShaneDelmore/b73d94b5a91edf338c34 to your computer and use it in GitHub Desktop.
sealed trait List2[+A] // `List` data type, parameterized on a type, `A`
case object Nil2 extends List2[Nothing] // A `List` data constructor representing the empty list
/* Another data constructor, representing nonempty lists. Note that `tail` is another `List[A]`,
which may be `Nil` or another `Cons`.
*/
case class Cons2[+A](head: A, tail: List2[A]) extends List2[A]
object List2 { // `List` companion object. Contains functions for creating and working with lists.
def sum(ints: List2[Int]): Int = ints match { // A function that uses pattern matching to add up a list of integers
case Nil2 => 0 // The sum of the empty list is 0.
case Cons2(x,xs) => x + sum(xs) // The sum of a list starting with `x` is `x` plus the sum of the rest of the list.
}
def product(ds: List2[Double]): Double = ds match {
case Nil2 => 1.0
case Cons2(0.0, _) => 0.0
case Cons2(x,xs) => x * product(xs)
}
def apply[A](as: A*): List2[A] = // Variadic function syntax
if (as.isEmpty) Nil2
else Cons2(as.head, apply(as.tail: _*))
def append[A](a1: List2[A], a2: List2[A]): List2[A] =
a1 match {
case Nil2 => a2
case Cons2(h,t) => Cons2(h, append(t, a2))
}
def foldRight[A,B](as: List2[A], z: B)(f: (A, B) => B): B = // Utility functions
as match {
case Nil2 => z
case Cons2(x, xs) => f(x, foldRight(xs, z)(f))
}
def sum2(ns: List2[Int]) =
foldRight(ns, 0)((x,y) => x + y)
def product2(ns: List2[Double]) =
foldRight(ns, 1.0)(_ * _) // `_ * _` is more concise notation for `(x,y) => x * y`; see sidebar
def tail[A](l: List2[A]): List2[A] = ???
def setHead[A](l: List2[A], h: A): List2[A] = ???
def drop[A](l: List2[A], n: Int): List2[A] = ???
def dropWhile[A](l: List2[A], f: A => Boolean): List2[A] = ???
def init[A](l: List2[A]): List2[A] = ???
def length[A](l: List2[A]): Int = ???
def foldLeft[A,B](l: List2[A], z: B)(f: (B, A) => B): B = ???
def map[A,B](l: List2[A])(f: A => B): List2[B] = ???
}
import List2._
val test = List2(1, 2, 3, 4, 5)
sum(test)
product(List2(1.0, 2.0, 3.0))
test match {
case Cons2(x, Cons2(2, Cons2(4, _))) => x
case Nil2 => 42
case Cons2(x, Cons2(y, Cons2(3, Cons2(4, _)))) => x + y
case Cons2(h, t) => h + sum(t)
case _ => 101
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment