Functional programming at code clubs

In my tech mentoring at Coder Dojo and Code Clubs I'm always on the look out for new things that broaden the mind, offer alternative approaches and get people thinking differently. So what about functional programming? How would that work at a code club? Is it even possible in Scratch?

Functional programming enables you to:
  • Write functions that take input and produce output with no side-effects, which makes them easy to reason about and test in isolation, and easy to share across projects
  • Use recursion to process lists of things, avoiding the work of loops and loop counters
  • Write higher-order functions that take other functions or blocks as input, making it possible to write custom logic or iteration blocks, such as for-each, map, filter or fold.
In addition, the functional programming approach helps you to think differently about algorithms, often resulting in a more concise, elegant solution to a programming challenge. Indeed, many mainstream languages have adopted functional features to bring these benefits to the programmer, see examples in Python and JavaScript.

MIT Scratch is the most popular programming language we use at code clubs and I've explored it to see if I can demonstrate functional programming. Unfortunately it's not possible to create blocks that return values (Reporter blocks -- Stack Overflow post) so I need another tool.

Snap looks like the answer. It's a extended reimplementation of Scratch that allows you to build your own blocks with many more options than Scratch. In the creator's words it is Scratch + the power of Scheme.

Modelling a flock of animals

To explore functional programming, we need an interesting app to create, how about Boids? Boids simulate the flocking behaviour of animals, such as birds or sheep. There are 3 simple to state rules:
  1. separation: steer to avoid crowding local flockmates
  2. alignment: steer towards the average heading of local flockmates
  3. cohesion: steer to move toward the average position (center of mass) of local flockmates
These are simple to state but harder to program! Here are some initial versions, click a title to see the code running in Snap.

Sheep Boids zero 

Let's start with a very simple version: here our sheep are moving randomly with no concern for each other. This has one new block (and nothing functional yet): if-on-edge-wrap — and nothing Scratch can't do:

Here our sheep are moving randomly, but they know when they are near another boid and flash. This has a new control block for-each:

So for every other clone we check the distance and switch costume if it's less than 60. The new for-each block makes it easy to do things to every element of the list, without having to do the usual loop work in Scratch. 

Here's the definition of the block, it takes a list and a code-block as parameters and uses recursion to work through the items of the list:

Sheep Boids 2 mouse

Now our sheep like the mouse pointer and move towards it. There are several new functions mostly to calculate the force applied to each sheep from the mouse, see them in the Operators section.

To do...

There's lots left to do:
  • The sheep move too fast, maybe they should have a maximum speed?
  • While we've shown how the sheep react to the mouse pointer, they don't react to each other yet —version 1d has a starting point for this behaviour
  • ...TBC
I'll add more as I explore at the code clubs...

A photo bank on your Raspberry Pi

I've been taking photos for years and now have many thousands, in fact too many to store on my laptop. My family take photos too, and we all like to share them.

None of us are particularly happy with Facebook or other online photo sharing sites, and anyway most of these are geared towards individual photographers, not a family of photo sharers.

As I'm a programmer I like to know how things work and strongly favour a solution where I can see and test the photo and metadata storage, so that I know that everything is safe. (And OK, yes, as a programmer I'm much more motivated to create my own solution rather than use an existing one!)

So how do we store and share our photos? Our solution: a Home Photo Bank. It's a safe place to store and share your family photos on your home network.

If you've got a spare Raspberry Pi around (or indeed any Linux or Mac computer), then follow this blog post to get your own photo bank up and running.

As well as photo storage and sharing, there are also tagging features so that you can categorise and discover related photos.

You can read a bit more about the photo bank on its GitHub page:

What you need:

  • A Raspberry Pi, model 2 or 3, running Raspbian
  • A router to plug it into, or use wifi
  • Some familiarity with the linux command line.

The set up:

Here's what we'll cover:
  • Set a hostname on your Pi so that your family can access it
  • Install packages: oracle-java8-jdk and mongodb
  • Install the application
  • Create cron 'reboot' entry to run the photo bank
  • Add a photo-uploader user, SSH keys and local scripts to make it easy to import files
  • Test that it works.

Set a hostname

Your family and friends (and anyone else on your home network) need to be able to access the photo bank. Set the Pi's hostname by editing /etc/hostname and then share the link http://photobank.local:3000/ - replace "photobank" with whatever hostname you gave your pi.

Install packages

Use apt-get to install the required packages: Java JDK for the runtime, and MongoDB for the data store and git to get the app itself.

sudo apt-get install oracle-java8-jdk mongodb git

Install the Photo Bank

There are five parts to the install:
  1. Install the build tool Leiningen
  2. Get the app source code
  3. Make media directories
  4. Set database credentials
  5. Run the app to download dependencies and start up the photo bank
To get Leiningen:

chmod +x lein

To get the app source code run: 

git clone

The photo bank stores photos in media directories. Create these before you run the app:

cd home-photo-bank/media
mkdir _import _process _failed

The media and database credentials are stored in the file profiles.clj -- create this file and add these lines:

    {:media-path "media"
     :database-url "mongodb://localhost/photo-bank" }}}

Now run the app, this will download all dependencies on the first run:

cd home-photo-bank
lein run

Now you should be able to browse to http://photobank.local:3000/

Check back soon for the rest of the detail...

My Education Manifesto

I've been involved in learning and education for over 5 years, enough time to start to make sense of my values and preferences -- what I stand for in education. So I've created a first draft education manifesto, to seek comment, feedback and discussion.

Why have a manifesto?

I want to explain to others what I'm up to in education, join forces with other like minded people, do a gap analysis and enable others to critique my approach.

(Format and ideas inspired by the Agile Manfesto

Education Manifesto

We are uncovering better ways to learn by doing it and helping others do it. Through this work we have come to value:
  • Learner led over leader led
  • Working on the learning environment over working on the learner
  • Intrinsic satisfaction over token rewards
  • Right pace over race to results
  • Deep understanding over memorisation
  • Working through struggle and mistakes over showing off perfection
  • Coaching and mentoring over micro-management
  • Questions from the learner over questions from the leader


  • Create an ideal environment for learning. Think about productive environments and the activity they encourage, e.g. library, workshop, artists studio, music practice room. 
  • Recognise energy now and choose task appropriately. If energy remains low, respect this and try something else.
  • Regular feedback to leader and learner to drive improvement. Respect learner's readiness for feedback and seek permission periodically (not continuously).
  • Deliberate practice builds mastery.
  • Connected learning to learner's needs + desires. "What does this mean for me?" is a great question.


Let me know what you think...

Tiling and tessellation with a Context Free Grammar - Part 2

In my previous blog post we looked at how to use a Context Free Grammar to make simple grids of circles and then use colour variation to produce a rainbow effect. Now let's look at making more interesting patterns of shapes.

Simple spirals

First let's draw a series of ever decreasing, spiralling triangles...

#lang s-exp stamps/lang

(define-shape spiral
  (spiral [r 22]
          [x .8]
          [s .95]))
(maximum-render-cycles 1000)
(start-shape spiral)

Play with those numbers in square brackets to produce something you like. Remember, r=rotation, x=x translation, s=scale.

Recursive loops

This example draws a hexagon with a circle of hexagons around it, and for each of those hexagons, it draws a circle of hexagons around it, recursively building up a pattern that fills the artwork.

#lang s-exp stamps/lang

(define-shape hex-circle
  ((loop ([i 6])
           [r (* 360 (/ i 6))]
           [y .9])))

(define-shape scene
  (hex-circle [alpha -.7]
              [b .2])

(maximum-render-cycles 1000)
(start-shape scene)

There's a few new concepts in this code:
  • A loop construct to draw a circle of 6 hexagons. There's a lot of brackets in there! These denote the loop; the binding, in this case i takes the values from 1 to 6; then the loop body, in this case a call to hex-circle with attributes to draw each at the right position around the central hexagon.
  • A bit of lisp-style maths: (* 360 (/ i 6)) means 360*(i/6), in other words, rotate by a sixth of a circle for each loop iteration. 
  • We use a scene function to set up the basic attributes, for everything drawn: reduced alpha (transparency) and reduced brightness.
As with previous examples, play with the numbers, or add in extra adjustments to create something you like.

Recursive branching

You may have noticed in the previous example that we drew many hexagons on top of other hexagons, resulting in dark hexagons in the centre of the pattern. As an alternative we can instead draw just two outer shapes, positioned at alternative angles (in this case -60˚ and 60˚), the effect of recursion then fills the plane.

#lang s-exp stamps/lang 

(define-shape C
  (C [r -60] [y .5])
  (C [r 60] [y .5])

(define-shape scene
     [alpha -.9]
     [b .2]))

(maximum-render-cycles 1000)
(start-shape scene)

Let's introduce a few variables to make playing with the numbers easier. This code is the pretty much the same as the above, but with the angle and space set at the start of the program (and red dots):

#lang s-exp stamps/lang 

(define angle (/ 360 8))
(define space 3)

(define-shape C
  (C [r (- angle)] [y space])
  (C [r angle] [y space])

(define-shape scene
     [alpha -.9]
     [b 1]
     [sat 1]
     [hue 0]))

(maximum-render-cycles 50000)
(start-shape scene)

What next? Let's explore tessellation with regular shapes such as pentagons, hexagons and heptagons... (coming soon)

Tiling and tessellation with a Context Free Grammar

There's something pleasing about filling a space with shapes that fit together and overlap in interesting ways. Using a Context Free Grammar we can use a simple language to express relations between shapes and make a large composition with a few rules.

In this series of blog post I explore tiling with different shapes, starting with simple grids and circular patterns with single shapes, then exploring more complex combinations of shapes. 

The tool I'm using to explore these patterns is Racket Stamps, which runs on the Racket language. Download both for free by following these links. 

What's a Context Free Grammar?

From Wikipedia a CFG is: "a set of production rules that describe all possible [compositions] in a given language... production rules are simple replacements."

So a CFG allows you to represent drawings by simple shape compositions, for example this Racket Stamps code draws an infinite line of circles by defining circles as a circle followed by circles to the left:

#lang s-exp stamps/lang
                        ;; Comments:
(define-shape circles   ;; define circles to be:
  (circle)              ;; a circle
  (circles [x 1]))      ;; followed by circles to the left

If you run that in Racket Stamps (and do check out the tutorial first) you'll see that the line is actually not infinite, just very long. We can control how far the rendering runs, and therefore how many shapes are drawn using the setting maximum-render-cycles -- you'll see this in the examples below.

Tiling a plane

So we can draw a line, but how would we fill a 2D space? The first method to try is to make a grid of shapes. A grid is a line of shapes, with a grid placed above it, which is a line of shapes with a grid placed above it... thanks to recursion we can fill the space, here's the code:

#lang s-exp stamps/lang

(define-shape line-of-circles
  (line-of-circles [x 1]))

(define-shape grid
  (grid [y 1]))

(maximum-render-cycles 1000)
(start-shape grid)

Because of the way the rendering works (and in particular how the maximum-render-cycles setting works), we actually get a triangle of circles! But we can crop into a square, so code like the above works well to help us explore patterns. Try this by adding this setting to the above example:

  (bounding '(-16 -12 -1 0.50))

Making adjustments

Do you see those xs and ys in the examples above, enclosed in square brackets? They adjust the position of shapes so that we don't draw everything on top of each other. There are lots of other adjustments you can use, try out the following:
  • rotate (or r) by a number of degrees
  • scale (or s) by a factor, 1 is same size, .9 is 10% smaller, 1.1 is 10% bigger 
  • shear by a factor between -1 and +1, 0 is no shear
  • hue (or h) change colour by degrees on the colour wheel 
  • saturation (or sat) between 0 and 1
  • brightness (or b) between 0 and 1
  • alpha (or a) between 0 and 1
In many cases the adjustment modifies the attribute by whatever you specify, so that you can gradually make things bigger or smaller, or change the colour. Try changing the definition of grid to the following:

(define-shape grid
  (line-of-circles [sat 1] [b 1]) ;; Full saturation and brightness
  (grid [y 1]
        [hue 10] ;; Move through the colour wheel by 10 degrees


Let's try to make something more interesting than a grid of circles... Tiling and Tessellation part 2.