Feeling Schemish

After a couple of decades of complaining how I miss Lisp, I was finally in the mood to get back to my roots today and do some coding in Scheme (used once upon a time in MIT's intro CS course Structure and Interpretation of Computer Programs, alas since supplanted by Python).

I created a github repo in which to mess around with some scripts and after a brief survey of current Scheme implementations settled on Gauche, which happens to be developed by my multitalented friend (pianist, actor, programmer...) Shiro Kawai.

For my first nostalgic trip back to the land of parentheses, I ported a processing script that calculates pi by simulating throwing darts at a circle, or more precisely within the bounding box of a circle, and then taking the ratio of darts in the circle to the total.

(use srfi-27)

(define (pi radius) ((piter radius 0 0)))

(define (piter radius inside total)
    (print (* 4.0 (/ inside (+ 0.000000001 total))))
    (if (incircle? (random radius) (random radius) radius)
        (piter radius (+ 1 inside) (+ 1 total))
        (piter radius inside (+ 1 total))))

(define (random range)
  (- (* (random-real) (+ range range)) range))

(define (incircle? x y radius)
  (< (+ (square x) (square y)) (square radius)))

(define (square x) (* x x))

That print call has a kludge constant to force a float conversion and avoid a divide by zero (double kludge!), but otherwise it looks nice and functional (I don't mind the parentheses, I prefer them to brackets and semicolons), and it's mostly self-contained, only using a library for the random-real call).

And after loading the script in gauche and typing (pi 10), it converges to somewhere in the pi ballbark.

3.1413629850086813
3.1413622087520783
3.1413624209284787
3.141362633104774
3.1413628452809648
3.141363057457051
3.1413622812013884
3.14136150494611
3.14136171712237
3.1413619292985246
3.1413621414745747
3.14136235365052
3.1413625658263604
3.1413627780020956
3.1413629901777265
3.141363202353252
3.141363414528673
3.141363626703989
3.141362850450488
3.1413620741973705
3.1413622863728605
3.141362498548246
3.141362710723526
3.1413629228987014
3.141363135073772
3.1413633472487374
3.1413635594235982
3.1413627831718403
3.1413629953467357
3.1413622190955004
3.1413624312704305
3.1413626434452553

Actually I wrote this script the first time in high school on an Apple II+, so those are my real programming roots. I don't envision going back to BASIC coding anytime soon, but who knows, maybe I'll get nostalgic about writing all those GOTOs again!

Subscribe to Technicat

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe