Phillip Trelford's Array

POKE 36879,255

Basic Tuples & Pattern Matching

Over the last couple of weeks I’ve been building my own parser, interpreter and compiler for Small Basic, a dialect of BASIC with only 14 keywords aimed at beginners. Despite, or perhaps because of, Small Basic’s simplicity some really fun programs have been developed, from games like Tetris and 3D Maze to a parser for the language itself.

Small Basic provides primitive types for numbers, strings and associative arrays. There is no syntax provided for structures, but these can be easily modelled with the associative arrays. For example a 3D point can be constructed with named items or ordinals:

Named items Ordinals
Point["X"] = 1.0
Point["Y"] = 2.0
Point["Z"] = 3.0
Point[0] = 1.0
Point[1] = 2.0
Point[2] = 3.0

In languages like Erlang and Python this could be more concisely expressed as a tuple:

Erlang Python
Point = {1.0, 2.0, 3.0}
point = (1.0, 2.0, 3.0)

In fact sophisticated Erlang programs are built entirely from tuples and lists, there is no explicit class or inheritance syntax in the language. Messages can be easily expressed with tuples and behaviour via pattern matching.

Alan Kay, inventor of the Smalltalk language has said:

The notion of object oriented programming is completely misunderstood. It's not about objects and classes, it's all about messages.

In Erlang a hierarchy of shapes can simply be modelled using tuples with atoms for names:

Circle = { circle, 5.0 }
Square = { square, 7.0 }
Rectangle = { rectangle, 10.0, 5.0 }

The area of a shape can be expressed using pattern matching:

area(Shape) ->
  case Shape of
    { circle, R } -> pi() * R * R;
    { square, W } -> W * W;
    { rect, W, H } -> W * H
  end.

Select Case

The Visual Basic family’s Select Case functionality is quite rich. More so than the switch/case statements of the mainstream C dialects: Java, C# and C++, which only match literals.

In Visual Basic it is already possible to match values with literals, conditions or ranges:

Select Case agerange
  Case Is < 16
    MsgBox("Minor")
  Case 16 To 21
    MsgBox("Still Young")
  Case 50 To 64
    MsgBox("Start Lying")
  Case Is > 65
    MsgBox("Be Yourself") 
  Case Else
    MsgBox("Inbetweeners")
End Select

Given that Select Case in VB is already quite expressive, it feels support for tuples and pattern matching over them would feel quite natural in the language.

Extended Small Basic

To this end I have extended my Small Basic parser and compiler implementation with tuple and pattern matching support.

Tuples

Inspiration for construction and deconstruction was taken from F# and Python:

F# Python
let person = ("Phil", 27)
let (name, age) = person
person = ("Phil", 27)
name, age = person

So that tuples use explicit parentheses in the extended Small Basic implementation:

Person = ("Phil", 27)
(Name, Age) = Person

Internally tuples are represented using Small Basic’s built-in associative arrays.

Pattern Matching

First I implemented VB’s Select Case statements, which is not hugely dissimilar to parsing and compiling Small Basic’s If/ElseIf/Else statements.

Then I extended Select Case to support matching tuples with similar functionality to F#:

F# Extended Small Basic
let xor x y =
  match (x,y) with
  | (1,1) -> 0
  | (1,0) -> 1
  | (0,1) -> 1
  | (0,0) -> 0
Function Xor(a,b)
  Select Case (a,b)
    Case (1,1)
      Xor = 0
    Case (1,0)
      Xor = 1
    Case (0,1)
      Xor = 1
    Case (0,0)
      Xor = 0
  EndSelect
EndFunction

Constructing, deconstructing and matching nested tuples is also supported.

Example

Putting it altogether, FizzBuzz can now be expressed in my extended Small Basic implementation with functions, tuples and pattern matching:

Function Mod(Dividend,Divisor)
  Mod = Dividend
  While Mod >= Divisor
    Mod = Mod - Divisor
  EndWhile
EndFunction

Sub Echo(s)
  TextWindow.WriteLine(s)
EndSub

For A = 1 To 100 ' Iterate from 1 to 100
  Select Case (Mod(A,3),Mod(A,5))
    Case (0,0)
      Echo("FizzBuzz")
    Case (0,_)
      Echo("Fizz")
    Case (_,0)
      Echo("Buzz")
    Case Else
      Echo(A)
  EndSelect
EndFor

Conclusions

Extending Small Basic with first class support for tuples was relatively easy, and I feel quite natural in the language. It provides object orientated programming without the need for a verbose class syntax. I think this is something that would probably work pretty well in other BASIC dialects including Visual Basic.

Source code is available on BitBucket: https://bitbucket.org/ptrelford/smallbasiccompiler

The Kids Are Alright

In the last week or so I've seen a popular article and a presentation which didn’t paint the rosiest of pictures for the next generation of coders:

I have to agree with Marc Scott that the Information & Communication Technology (ICT) GCSE widely studied in the UK, with Microsoft Office as a focus, seems a bit of a step backwards. The Computer Studies O-level I remember from the mid-80s put coding front and centre. I still have fond memories of my end of year project which consisted of a sprite designer written in Z80 assembler and extensions to the system’s basic language for games programming.

computermuseum

Kids Code

But not everyone at school in the 1980s did Computer Studies or was writing games in their bedroom. What are kids doing in the 21st century? My eldest son Thomas has a range of interests including playing the piano, chess, swimming, scouts, playing video games and coding. His common-or-garden state school has a computer club where they practice Python programming, but unfortunately it is so oversubscribed he couldn’t get a place. He does however write code at home for fun, and believe it or not most of what he has learnt has been off his own back. He started out making his own 3D levels in the Roblox game when he was about 9, and soon progressed to adding his own scripts written in Lua. To give him a little encouragement I bought him a book, Roblox Lua programming written by a teenager. More recently he's been playing with Python on the Raspberry Pi.

Now not all the kids at my son's school code, but quite a few of them do.

Kids Conferences

Thomas has also come along with me to a few conferences and game jams. Last year he came to the Progressive F# Tutorials in London, learning the syntax of the language from Chris Marinos’s F# Koans. Then he managed to make some tunes in Rob Pickering’s Undertone session. Here he is putting a question to the panel:

thomas

Thomas is not alone in knowing F#, here is a 1-hour crash course taught to Year 6 students (11 year olds) at a school in Cambridge: http://fssnip.net/jc

He’s also been to some game jams with me, where he’s mostly worked on the music and sound effects. I’ve seen quite a few kids at this type of event. Here’s a picture of us from last weekend’s GameCraft jam at Skills Matter in London:

GameCraft

Last weekend also saw a national Festival of Code in the UK from Young Rewired State:

yrs-crowd

This fall sees a GOTO conference for kids in Denmark:


I think it would be great to see the trend for kids in conferences continue, and it fills me with hope for the future of programming.

Dark Matter

Brett Victor’s talk on the Future of Programming is well worth a watch, he presents a vision of the future based on what was known in 1973, using an over head projector (OHP). One suggestion is that if programming is still dominated by low-level programming languages in 40 years time (which it is) then something has gone seriously wrong.

dark-matter-doubts_1

After talking about kids going to major developer events, the shame is that the vast majority of existing enterprise developers will have never been to one. These are the unseen 99% Scott Hanselman refers to as Dark Matter Developers:

They don't read a lot of blogs, they never write blogs, they don't go to user groups, they don't tweet or facebook, and you don't often see them at large conferences

I suspect these “Dark Matter Developers” are being spoon fed their information directly from vendors like Microsoft (MSDN) and Oracle (Java).

Speaking at conferences can often feel like you’re preaching to the converted. Perhaps the real opportunity is mentoring the next generation, because you know the kids are alright.

GameCraft NYC

gamecraftSkills Matter are excited to host the first ever New York GameCraft event on Friday 20th September at the DUMBO Loft! Following the phenomenal success and excitement around Dublin GameCraft, the event is now going global with a event also planned in London! GameCraft is a games jam event designed around building the gaming community. We aim to create events which allow game-makers to meet, share ideas, have fun, compete for prizes and most importantly make games. The events will be facilitated by Games experts (and enthusiasts!) Andrea Magnorsky and Phil Trelford.

 

This is a free event on the same week at the same venue as the Progressive F# Tutorials NYC, so why not come and join us for both. F# + MonoGame makes a pretty awesome combination, as does Lua + Love or Python + PyGame. Take a peek at the excellent GameCraft resources page for some great links to game engines and tools.

Check out the recent article on GameCraft in the Irish Times. I popped over to Dublin for the first event back in February 2012 and it was really well organized and great fun. I managed to knock up a simple game in under 6 hours. The London event on Saturday August 10th will be 12 hours which may be enough to create a releasable game. Currently my hope is to take a simple game concept to completion and release it on an app store on the same day!

Hope to see you there.