Skip to content

Instantly share code, notes, and snippets.

@debasishg
Created July 2, 2011 09:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save debasishg/1059896 to your computer and use it in GitHub Desktop.
Save debasishg/1059896 to your computer and use it in GitHub Desktop.
Tony Morris - catamorphism with cons list
// Church-encoded cons list
trait MyList[A] {
def foldRight[B]: (A => B => B) => B => B
}
object MyList {
def nil[A]: MyList[A] = new MyList[A] {
def foldRight[B] =
_ => z => z
}
def cons[A](h: A)(t: MyList[A]): MyList[A] =
new MyList[A] {
def foldRight[A] =
f => z =>
f(h)(t.foldRight(f)(z))
}
// Mutual inverses
def -->[A](a: List[A]): MyList[A] =
a.foldRight(nil[A])((a, b) => cons[A](a)(b))
def <--[A](a: MyList[A]): List[A] =
a.foldRight[List[A]](a => b => a :: b)(Nil)
// Mutual inverses
// scala.List[A]=MyList[A]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment