Category Archives: Programming Languages

The GRAIL Project

In 1964 the RAND corporation unveiled the GRAIL Project. GRAIL was an early example of a GUI, and (the first?) example of a tablet.

The system used a programming language called GrailLanguage, which was a high-level flowchart-based programming language. All programs were written graphically and with a pen, using character recognition for statements and shape recognition for flow control.

Watch this video and tell me that the best new talent is working on Groupon for Babies or a better way to share photos.

Tagged , , , , , , ,

Want To Make Your R Charts Look Like The Economist?

Want to make your R charts look like the ones placed in The Economists?
Link.

Tagged , , , , , ,

The Value of Immediate Feedback

You may have heard of Bret Victor from his “Kill Math” project and the beautiful differential equation playground that he has created with his Interactive Exploration of a Dynamical System.
It caused quite a stir a while ago and since then we have seen Apple take on some of those ideas in its new eBook push. Even if you’ve seen it before it is definitely worth a refresher viewing:

Since then, Bret has apparently been quite busy building some proof-of-concept tools for designers and weaving together some of his ideas into an amazing talk.
The talk showcases UI concepts that allow programmers and designers to interact with their creation directly instead of through symbol based abstraction, the idea being that such symbol based abstractions are better suited for paper than the digital canvas and create a barrier between the creator and their creation.
In a few short demos Bret shows how powerful developer/designer tooling can truly be. These livecoding demos really showed me how valuable immediate feedback can be.
I have often ‘played’ with an algorithm in a dynamic/exploratory environment such as MATLAB when trying to solve a problem, and then when I have a handle on how the data feels re-implement the algorithm into another language to integrate with the rest of the system. After seeing this video I’ve decided that kind of workflow can be improved. Visualisation should not be an afterthought. It should be implemented first.

This video is well worth your time:

Tagged , , , , , ,

Multithreaded access to a SQLite database

If you use SQLite like me you’ll know that it is amazingly powerful, convenient, and compact. However if you have an app that needs to do a lot of database IO concurrently with SQLite you may run into the fact that it is classically single-threaded and does not give you the guarantees that are present in normal RDBMS systems. Here is a nice writeup of a few of the strategies you can use to perform SQLite reads/writes in a multithreaded app. Worth a read if you use SQLite. Link.

Tagged , , , ,

Functional Spreadsheet in F#

For anyone interested in how to solve a real problem using F#, I suggest reading this post on Developer Fusion. It is an implementation of the core functionality of a spreadsheet. It includes a full parsing and expression evaluation engine, plus databinding and display (silverlight… eww, but it’s mainly so you can try it in your browser). Reading it and looking at the use of Active Patters, Pattern Matching and Discriminated Unions really drives home how language features can lead to clear and concise implementations of algorithms that are often awkward to implement in true OO fashion.

The full code snippet is available here, and can be run inside your browser here.

Recommended.

Tagged , ,

Programmer Fluency

A few weeks ago I came across a really interesting comment on Slashdot (I think I found it linked on Hacker News).
A poster by the name of wrook posted this comment that deserves to be widely read.

I’m quoting some of it here (all credit to the original poster).

My current theory is that programming is quite literally writing. The vast majority of programming is not conceptually difficult (contrary to what a lot of people would have you believe). We only make it difficult because we suck at writing. The vast majority of programmers aren’t fluent, and don’t even have a desire to be fluent. They don’t read other people’s code. They don’t recognise or use idioms. They don’t think *in the programming language*. Most code sucks because we have the fluency equivalent of 3 year olds trying to write a novel. And so our programs are needlessly complex.

Those programmers with a “spark” are programmers who have an innate talent for the language. Or they are people who have read and read and read code. Or both. We teach programming wrong. We teach it the way Japanese teachers have been teaching English. We teach about programming and expect that students will spontaneously learn to write from this collection of facts.

I think that being fluent is the most important skill a programmer can have. It leads to more maintainable and readable code. Any idiot can write code that a machine can understand, only a great programmer can write code that other people can understand.

Tagged , , , ,

10 One Liners to Impress Your Friends

As a bit of a programming language geek I find that comparing programming languages is a worthwhile exercise mainly because of the different techniques and styles that you are exposed to.
Learning multiple programming languages is one of the best things you can do to gain intuition about the most expressive way to write your code in any language.
No matter how much of an expert you are in a given language, learning a new one is often a humbling and educational experience and one that we should all try to do every so often to keep ourselves sharp.

I’ve seen several articles going around showcasing ‘one-liners’ (single lines of code) in different languages to perform a set of 10 simple tasks.
The first one I saw was done in Scala, and quickly spawned a number of imitations in other languages:

They are worth a look if only for a nice take on FizzBuzz – the Jeff Atwood smoke-test of programmer competency:

Enumerable.Range(1, 15).Select((i)=>i + (i%3==0?"fizz":"") + (i%5==0?"buzz":""));

C# is getting much more expressive with LINQ extension methods and lambda expressions but I think F# still has the edge with some of the inbuilt list processing functions.
Take partitioning a list into two lists based on a predicate in C#:

var passed = new List<int>();
var failed = new List<int>();
(from bucket in new[] { passed, failed } from i in new[] { 49, 58, 76, 82, 88, 90 } select new { bucket, i }).ToList().ForEach((tuple) => tuple.bucket.AddRange(Enumerable.Repeat(tuple, 1).Where((tup) => (tup.bucket == passed && tup.i > 60) || (tup.bucket == failed && tup.i <= 60)).Select((tup) => tup.i)));

Now in F#:

[49; 58; 76; 82; 88; 90] |> List.partition (fun i -> i > 60);;

If you look at the links above and see which language is most expressive for solving each problem you can really start to understand how languages can affect productivity.
Just being Turing Complete isn’t enough these days, and thank god for that

Tagged , , , ,

A C# to JavaScript Compiler

This is well worth checking out for programming language geeks and web technology geeks alike.

Kevin Gadd has posted a project to his GitHub account called JSIL.
It compiles C# code to JavaScript code that is runnable in a modern browser. Furthermore it wraps the XNA framework for game development on PC and Xbox, allowing the graphics to be rendered to an HTML5 canvas.

He has also compiled the XNA Platformer Starter Kit example which ships with XNA and it is playable in your browser right now.

Imagine writing a single codebase and deploying to Xbox, PC, Windows Phone, and HTML5…

Tagged , , , , ,

Y-Combinator in Objective-C

A GitHub user named Joshua Ballenco recently posted a project called y.h.
It’s an implementation of the Y-Combinator which is used in functional programming to achieve recursion using anonymous functions.
Apple is lucky to have talented people trying to make their language nicer to use.
Apple did well adding Blocks(closures) to Objective-C which slightly modernises the language. Unfortunately even with (because of?) Cocoa it’s not very expressive…

I mean look at this:

RecurBlock factorial = YComb((NSNumber *) ^(NSNumber *val) {
if([val compare: [NSNumber numberWithInt: 0]] == NSOrderedSame) {
return [NSNumber numberWithInt:1];
} else {
NSNumber *next_val = this_block([NSNumber numberWithInt:([val intValue] - 1)]);
return [NSNumber numberWithInt:([val intValue] * [next_val intValue])];
}
});

Could well be the least expressive implementation of a recursive factorial ever.
I’m not sure I know what to say…

Maybe MacRuby will save us all!

Tagged , , ,

Pattern Matching in C#

Many functional languages have the construct of ‘pattern matching’ baked in to the language.
OCaml, F#, and Haskell all use it as a concise, expressive, and safe (we’ll get to that later) way to handle flow control or even to define entire functions.
In F# it looks like this:

let login user =	
match user with	
 | "hypermush" -> printfn "Hello, Martin"	
 | "admin" -> printfn "Hello, Sir"	
 |  x -> printfn "Hello, %s" x;;

This may look simple, but there is a lot going on here.
Using the match syntax we take the value (in this case ‘name’) and test if it matches any of the patterns (the expressions on the left hand side of the ‘->’).
The first pattern to match executes the statement on the right hand side of the arrow. We then leave the statement.
The first thing to notice is that the first two patterns match string literals while the last actually binds the value name to x and uses that value in the continuation function.
The second thing to notice is that these continuation functions may have side effects and call other functions (or recurse), which allows us to write nontrivial functions that consist entirely of a pattern match. It’s not hard to see how pattern matching is concise and expressive compared to a bunch of if/else blocks, but how is it ‘safe’?
Well, in a strongly typed language like F# with fancy type-inference the compiler can give you warnings that let you reason about the correctness of a program. When you use pattern matching you are being explicit with your intent to dispatch and this can be powerful.

For example, if your patterns are incomplete (ie. there is a case for which you have not specified a continuation), the F# compiler will warn you:

let who l =	match l with	
 | 'Me' -> 1 	
 | 'You' -> 2;;


FS0025: Incomplete pattern matches on this expression. For example, the value '' '' may indicate a case not covered by the pattern(s).

Let’s say you ignore the warning and continue on. At runtime, failure to match a pattern will cause an exception to be thrown:

Microsoft.FSharp.Core.MatchFailureException: The match cases were incomplete
This stands in stark contrast to a bunch of if..else statements where one can ‘fall out’ and potentially leave the program in an unknown state.

Speaking of state… The match construct also frees us from having to manage our match state manually.

No temporary variables are created by the programmer – we don’t even explicitly store the value we’re matching!
Let’s say we have this C# code:

if(predicate1)
{	
       if(predicate2)
       {		
              predicate1and2action();
       }	
       else
       {		
              predicate1action();
       }
}
else if(predicate2)
{	
        predicate2action();
}

That is a lot to think about and in complicated cases it can difficult to get this right.

We have multiple exit points far apart in the function and it can be difficult to reason about the program just by looking at it. Compare with pattern matching:

let orFunc x y = 	match x, y with	
 | true, true -> true 	
 | true, false -> true	
 | false, true -> true 	
 | false, false -> false;;

The inline predicates and lack of nesting make clear the purpose and result of the function for all the possible inputs.
Pattern matching is also a nice way to encapsulate behaviour for injection into other parts of a program. The flow control including any side effects is captured and can be passed around as an object into a higher-order dispatcher (perhaps another matcher!). Because the continuations are only executed when the pattern is matched, passing around the matcher is efficient as the evaluation of the continuations is lazy.

F# and Haskell have really nice syntax for pattern matching and when combined with strong type inference, pattern matching becomes a standard way to express behaviours in a functional program.
For those of us using C#, C# 3.0 gives us the nicer ‘lambda’ syntax for anonymous methods and so makes it feasible to implement a simple pattern matching class.
That’s exactly what I have done.

The source is available on GitHub here.

You can match literals:

Matcher<int>	
.Match(5)	
.With(5,x=>System.Console.WriteLine("5!"))
.Go(); 

Here, 5 is the pattern being matched and x=>System.Console.WriteLine(“5!”) is the continuation function.
Matcher will throw an Exception if provided a value that matches no pattern.
(The implementation uses .Equals() to determine object equality, so if you want to use literal matching in C#, you should use it only with a proper immutable data type that overrides .Equals())
If you want to create a ‘catch all’ pattern, you can use Else(). This pattern will be checked only after all other defined patterns have been examined.

Matcher<int>	
.Match(5)	
.With(5,x => System.Console.WriteLine("5!"))	
.Else(x => System.Console.WriteLine("Not 5!"))	
.Go(); 

These are all well and good, but the continuation functions all have side effects. What if we want to be purely functional? We would need to return a value from our matcher…

bool result = Matcher<int,bool>				
.Match(6)				
.With(5,x => true)				
.Else(x=>false)				
.Go();

Now we can at least use a matcher as the entire body of a method. However, we’re still matching literals, both in how we retrieve the value, and our pattern for matching it.
This isn’t necessary at all – in fact this is all just sugar. Both the value accessor and pattern match predicate are functions themselves, the type signatures tell the story:

public static Matcher<T,TReturn> Match(Func<T> accessor) 
public Matcher<T,TReturn> With(Func<T,bool> predicate,Func<T,TReturn> continuation)

At least now we can do this:

public int RecursiveFunction(int y)
{	
return Matcher<int,int>		
.Match(y)		
.With(x=> x > 0, x=> RecursiveFunction(x - 1))		
.Else(x=> x)		
.Go();
}

Now we’re talking!
Check out the unit test project for some more code samples.

(This blog post was written on the plane from San Francisco to Melbourne but I didn’t get a chance to post it until Christmas Day, so Merry Christmas everyone!).

Tagged , , , , ,