The implementation of Scheme that serves as a companion to this text includes Turtle graphics, an illustrating environment developed as part of the Logo language (another Lisp dialect). This turtle begins in the center of a canvas, moves and turns based on procedures, and draws lines behind it as it moves. While the turtle was invented to engage children in the act of programming, it remains an engaging graphical tool for even advanced programmers.
At any moment during the course of executing a Scheme program, the turtle has a position and heading on the canvas. Single-argument procedures such as forward and right change the position and heading of the turtle. Common procedures have abbreviations: forward can also be called as fd, etc. The begin special form in Scheme allows a single expression to include multiple sub-expressions. This form is useful for issuing multiple commands:
> (define (repeat k fn) (if (> k 0) (begin (fn) (repeat (- k 1) fn)) nil)) > (repeat 5 (lambda () (fd 100) (repeat 5 (lambda () (fd 20) (rt 144))) (rt 144))) nil
The full repertoire of Turtle procedures is also built into Python as the turtle library module.
As a final example, Scheme can express recursive drawings using its turtle graphics in a remarkably compact form. Sierpinski's triangle is a fractal that draws each triangle as three neighboring triangles that have vertexes at the midpoints of the legs of the triangle that contains them. It can be drawn to a finite recursive depth by this Scheme program:
> (define (repeat k fn) (if (> k 0) (begin (fn) (repeat (- k 1) fn)) nil)) > (define (tri fn) (repeat 3 (lambda () (fn) (lt 120)))) > (define (sier d k) (tri (lambda () (if (= k 1) (fd d) (leg d k))))) > (define (leg d k) (sier (/ d 2) (- k 1)) (penup) (fd d) (pendown))
The triangle procedure is a general method for repeating a drawing procedure three times with a left turn following each repetition. The sier procedure takes a length d and a recursive depth k. It draws a plain triangle if the depth is 1, and otherwise draws a triangle made up of calls to leg. The leg procedure draws a single leg of a recursive Sierpinski triangle by a recursive call to sier that fills the first half of the length of the leg, then by moving the turtle to the next vertex. The procedures penup and pendown stop the turtle from drawing as it moves by lifting its pen up and the placing it down again. The mutual recursion between sier and leg yields this result:
> (sier 400 6)