cons in CoffeeScript


I’ve had a copy of SICP for a while but recently decided to watch the videos. There are some great moments in the lectures. Abelson and Sussman seem able to explain things I already know but deepen my understanding just by the way they get there. One of my favorite moments is when Abelson talks about writing cons, car and cdr with lambda and remarking that data is created from thin air…

This is cons, car and cdr implemented in CoffeeScript. First, a couple of tests in cons.spec.coffee

assert = require 'assert'
{cons, car, cdr} = require './cons.coffee'

#it should cons two numbers
do () ->
  nums = cons 2,3
  assert.ok car(nums) is 2
  assert.ok cdr(nums) is 3

#it should cons two conses
do () ->
  quad = cons cons(2,3), cons(4,5)
  assert.ok car(car(quad)) is 2
  assert.ok car(cdr(quad)) is 4

Then the implementation in cons.coffee:

cons = (x,y) ->
  (m) ->
    m x,y

car = (x) ->
  x (a,d) ->
    a

cdr = (x) ->
  x (a,d) ->
    d

If you don’t see why this is interesting, do yourself a favour and watch the SICP videos or buy the book.



CoffeeScript in Action


CoffeeScript in Action book cover

I'm the author. Get it from Manning.