Skip to content

Instantly share code, notes, and snippets.

@yllan
Created December 6, 2011 02:58
Show Gist options
  • Select an option

  • Save yllan/1436494 to your computer and use it in GitHub Desktop.

Select an option

Save yllan/1436494 to your computer and use it in GitHub Desktop.
Scala gist
// Ugly version but works
def cons(a:Any, b:Any) = (m:Any)⇒m.asInstanceOf[Function2[Any,Any,Any]](a,b)
def car(z:Any) = z.asInstanceOf[Function1[Function2[Any,Any,Any],Any]]((a:Any,b:Any)⇒a)
def cdr(z:Any) = z.asInstanceOf[Function1[Function2[Any,Any,Any],Any]]((a:Any,b:Any)⇒b)
// Try with type parameter, failed.
def cons[A,B,Z](a:A, b:B) = (m:(A,B)⇒Z)⇒m(a,b)
def car[A,B](z:((A,B)⇒A)⇒A) = z((a:A, b:B)⇒a)
def cdr[A,B](z:((A,B)⇒B)⇒B) = z((a:A, b:B)=>b)
scala> car(cons(1,2))
<console>:10: error: type mismatch;
found : (Int, Int) => Nothing => Nothing
required: (Int, Int) => Int => Int
car(cons(1,2))
^
// Test
car(cons(1,2))==1
cdr(cons(1,2))==2
car(cons(1,cons(2,3)))==1
car(cdr(cons(1,cons(2,3))))==2
cdr(cdr(cons(1,cons(2,3))))==3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment