Skip to content

Instantly share code, notes, and snippets.

@sshark
Last active December 19, 2015 18:35
Show Gist options
  • Select an option

  • Save sshark/2dc2e380d5d231dbd2fb to your computer and use it in GitHub Desktop.

Select an option

Save sshark/2dc2e380d5d231dbd2fb to your computer and use it in GitHub Desktop.
Oversimplified List and reverse functions implementations for learning purpose
sealed trait LList[+A] {
def ::[B >: A](b: B): LList[B]
def ++[B >: A](b: LList[B]): LList[B]
}
case object End extends LList[Nothing] {
def ::[B](b: B) = Cons(b, End)
def ++[B](b: LList[B]) = b
}
case class Cons[A](a: A, l: LList[A]) extends LList[A] {
def ::[B >: A](b: B) = Cons(b, Cons(a, l))
def ++[B >: A](b: LList[B]): LList[B] = {
def _concat(ls: LList[B]): LList[B] = ls match {
case End => b
case Cons(x, xs) => Cons(x, _concat(xs))
}
Cons(a, _concat(l))
}
}
val a = Cons(1, End)
val b = 2 :: a
val c = b ++ Cons(3, End)
import scala.annotation.tailrec
def rReverse[A](l: LList[A]): LList[A] = {
@tailrec
def _rev(l:LList[A], acc:LList[A]): LList[A] = l match {
case Cons(x, xs) => _rev(xs, Cons(x, acc))
case End => acc
}
_rev(l, End)
}
rReverse(c)
def reverse[A](l: LList[A]): LList[A] = l match {
case Cons(x, xs) => reverse(xs) ++ Cons(x, End)
case End => End
}
reverse(c)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment