axelhodler

Learning Scheme with TDD

For some time now i wanted take a dive into functional programming by working through the SICP Book, which is a classic text in computer science and older than myself. The examples in the book are using [Scheme](https://en.wikipedia.org/wiki/Scheme_(programming_language). Scheme follows a minimalist design philosophy by specifying a small standard core with powerful tools for language extension.

Intrigued by a screencast in which Kent Beck uses TDD to learn CoffeeScript i wanted to take a similar approach to learning Scheme.

In the following paragraphs i will describe the necessary setup steps to work through the examples following TDD.

Unit Testing Setup

A search for Scheme and Unit Testing will lead you to Ward Cunningham’s Wiki. With the information there we can put together a simple unit testing ‘framework’.

(define (report-error msg)
  (error (string-append "assertion: '" msg "' has failed")))

(define (assert-that msg assertion)
  (if (not assertion) (report-error msg)))

Let’s deconstruct the provided snippet.

(define (report-error msg)
  (error (string-append "assertion: '" msg "' has failed")))
)

As you might have guessed, this method is for providing error messages. The string-append function takes strings as arguments and concatenates them to a single string. It will construct our error message. error takes a string and creates an actual error. With define we can define the function report-error which takes the custom part of our error message as an argument.

(define (assert-that msg assertion)
  (if (not assertion) (report-error msg)))

The second function will provide us with the function assert-that to make assertions. not will return true if the argument is false and false if the argument is true.

(not (> 1 2))

Will therefore return #t since 2 is not less than 1.

This means that if our assertion is false then (not assertion) will return #t, report-error will be invoked and we’re left with the AssertionError.