Colourful Random Walks in Processing

A language suited for quickly prototyping your ideas

Processing is a great language for quickly prototyping and designing visual representations of processes. Built on top of Java, it provides a great layer of abstraction that takes away a lot of the verbosity of Java, allowing you to focus purely on creating your sketch (what Processing calls its programs). A quick search online will reveal some wonderful visual eye-candy created within the language, as well as representations of complex data processes, such as fractals and cellular automata, to evolutionary, physics and A.I simulations. Indeed, it’s a language well-suited to scientists and mathematicians just as it is to graphic designers and digital artists.

It’s also supported by a whole host of user-created libraries to extend to the language even further, offering a good level of extensibility in many different areas of programming.

 

The Sketch

Just as an example of what is possible in a short amount of time with Processing, I decided to experiment with random walks. I wanted to visually represent the walk by changing its colour at every single step, however the colours changed so frequently that it looked like a jumbled mess. It looked more like image noise than any sort of representation of a Random Walk, so that wasn’t going to work.

So, instead of randomly changing colour at every step/iteration, I added in a counter that changed the walker to a random colour value every 5000 iterations;

A random walk in processing

A random walk in Processing using random RGB values.

While this is visually appealing to look at when the walk doesn’t cover too much of the application window (right), it quickly becomes rather garish after many iterations, as is apparent on the left-hand side of the image.

So in the next version of the sketch, I created an array of colours (represented by hex values) that worked well together, and passed that array into my walker object’s constructor. Inside the Walker class, I pick a random index value from the array, and assign the hex value stored at that position in the array to be the colour of the walker every 5000 steps;

A random walk in processing

A random walk in Processing using a random hex value from a predefined set of colours.

Many more iterations later

Even after many iterations, with fewer colours, and by using a complementary colour-set, the effect is much nicer to look at;

A random walk in processing

Many more iterations later.

All of this took surprisingly little code, thanks to Processing. A little under 70 lines of code, including white-space. A great language to learn, whether you’re new to programming, or an experienced programmer.

Because Processing abstracts out a lot of the underlying Java code, it allows you to be much more succinct, without compromising on any of the syntactic sugar that makes Java an easy object-oriented language to work with.

Function overloading in PHP

Why it is and isn’t supported.

 

Although PHP doesn’t handle function overloading in quite the same way as some strongly typed programming languages, it does support the ability to overload functions. Just in a different way.

Because PHP uses type inference to deduce the type of values your variables contain, it isn’t able to differentiate between two functions of the same name with different parameters.

For example, if we wanted to create an add() function that could add two numbers, or concatenate two strings, in some languages we could write something like this;

The first thing you may notice if you use an IDE is that it reports an error. In NetBeans, we get the following error:

Method or function “add” has already been declared

PHP doesn’t allow you to declare two functions in the same namespace with the same name. This is because If you were to invoke the function, it wouldn’t know which of the two functions you meant to call. Although PHP supports explicit type casting, it does not support declaring a variable of a particular type, so it doesn’t support “classic” function overloading. The php.net manual refers to this as Type Juggling.

 

Solution: One function, and a little extra logic.

 

Okay, maybe more than just a little.

PHP has several built-in functions which allow you to access the parameters of a function. This is what gives you the ability to overload your functions. Although the syntax is somewhat more verbose, it is possible to achieve function overloading in much the same way as the example above. However, instead of creating multiple functions with the same name, you create one function, and call different code blocks based on the number and the type of parameters. The main difference here is that you have to do it in a very explicit way.

When function_num_args() is called inside a function, it will return the number of parameters that were passed to the function during that function call. Using this, we can specify which section of code we want to run, based on the number of parameters passed into the function when it is called.

func_get_arg() allows us to access the values passed to the called function. The function takes a zero-based index value, so the first parameter is at position 0, the second at position 1, and so on.

Finally, we can call the is_string() and is_int() functions on the returned values. These functions will return either true or false, based on whether the values passed to them are integers or strings, respectively. There are several of these functions available in PHP. For example, if we wanted to handle floating point numbers as well, we could use the is_float() function. Using additional logic, we could call the same block of code whether a number is a floating point or an integer value, or handle these types of number entirely differently.

Now when we call the function;

 

 

Should you use it?

 

This is entirely up to you. It could be argued that function overloading in this manner violates the Separation of concerns principle (although it is a principle, not a hard-and-fast rule). Provided the code is readable and easy to maintain, and makes sense for its purpose, then used wisely, it can add additional flexibility to your code when handling various data-types. You might, for example, want to round floating point numbers to a certain level of precision, or ensure integer values are always returned to two decimal places, such as when dealing with currency values.

Multidimensional arrays of any depth in PHP

Creating multidimensional arrays in PHP

There are times when you need to generate an array structure in advance of the data you want to store inside it. In most cases when I need this, I’ll create a few for loops to create my array structure, and insert my data as I build up my array. While this is fine, it can get a little messy for arrays of more than two or three dimensions, so a clean approach is to separate the array generation from the array content generation. You can always iterate over your array after you’ve generated it.

Recently, I needed the ability to create an array of any depth, so I wrote a function that would allow me to do so. PHP’s arrays are dynamic, but the built in array() function in PHP doesn’t allow you to specify a size when you create an array. However, because arrays in PHP are dynamic, it’s very easy to create dynamically sized arrays on the fly.

The code:

If we want to create a 3×3 array:

If you wanted to create a 3x3x3 array, you can use create2dArray() with the PHP built-in function array_fill():

If you wanted to create a 3x3x3x3 array, aka a 4-dimensional array:

Using a combination of the techniques above, you can create an array of any depth, and you can tailor the create2dArray() function to your specific multi-dimensional array-creating needs.

Multidimensional arrays can be a little tricky to get your head around at first, so if you’re having trouble visualising what your multidimensional array looks like, use this snippet:

Let’s go one step further. You might not even know what level of depth your array will need to be at run-time, so it would be great if you could dynamically determine what level of depth you want your array to be via user-input or some other method, and then generate your array based on those values.

Now, using both createDynamicArray() and create2dArray(), we can create an array of any depth dynamically;

Create a 4x4x3x3x2x2 array:

Create a 4x4x3x3x10 array:

Tokenizer, a simple lexer in PHP to extract tokens

Tokenizer V1.0.0

Recently, after discovering Emmet for Sublime Text 3, my interest in parsing grammars and generating my own basic programming language and syntax was rekindled. Having the ability to use a simple, easy to understand syntax to quickly generate common boilerplate code (or, in the case of Emmet, html) is a tempting prospect.

Why build a Lexer?

Although most modern PHP IDEs do have snippet support; the ability to create re-usable sections of code, they’re not grammars. You can’t use them to construct code from many little building blocks or keywords. Just one at a time. Snippets are useful, though. If you find yourself writing for loops on a regular basis, then having a keyword you can type into your editor that quickly expands into a for loop ready for programming is a life saver.

But what if you wanted nested for loops? Or a for loop within a for loop, with three nested if statements inside it, followed by a while loop proceeding the first for loop? Yes, you could use snippets, but they wouldn’t be quite as fast. It would be nice to have a syntax as simple as Emmet’s, but designed specifically for PHP.

My first attempt at creating a Lexer was all-too basic, and I found myself trying to write an ever-more complex regular expression to try and extract all the tokens I wanted from my string. Which is why I decided to build a simple Lexer class, instead.

Tokenizer in action

Output:

This is a basic example of the tokenizer in action. You create a series of patterns to match using regular expressions, and the tokenizer will take an input string and extract the tokens from it. If the tokenizer encounters any problems, it will report where in the patterns array the error occurred.

Why PHP?

Why not? As a scripting language, PHP makes it much easier to focus on developing the language itself than getting too bogged down in the syntax of a more complex programming language. This may be at a performance cost due to PHP being an interpreted language, though. However, one of the benefits of an interpreted language like PHP, Javascript or Python is the function eval(). This function interprets a string as inline code, and then processes it as code. Although some people will tell you eval() is evil, I think it’s just misunderstood. Let’s say you wanted to a parse a mathematical expression in your new programming language, and return the result. You could write your own math parser. Going through the process of adding in operator precedence, including parsing expressions in brackets first, or..

However, if you had performance in mind, but still wanted to maintain the ability to have some of the work done for you, then you could look at Lua and ChaiScript, two scripting languages you can use within C++. This gives you the performance of a compiled language, and the flexibility of a scripting language, all in one.

What next?

There is of course much more to creating a programming language than just recognising the individual tokens the syntax is made of. Once you have your tokens, you’ll need to parse them with a parser which can then interpret the tokens as a grammar, and then perform actions based on that grammar. One common approach is creating what is known as an abstract syntax tree. This can be accomplished by using the Interpreter design pattern, for example.

There are also pre-built lexers and parsers out there if you want a good head start, such as ANTLR and Bison, however you may find building your own will give you a much better understanding of how grammars can be built. I recommend looking into Chomsky hierarchy and Backus–Naur Form as they’re a good place to start.

If you’re looking for a light introduction into building a simple programming language, howCode have an excellent set of tutorials on their youtube channel. The playlist can be found here. The tutorials are written in Python, but the techniques can be applied to a variety of different imperative programming languages such as PHP, C++, Java and even Javascript.

Download Tokenizer on Github

The example.php file on github includes a more fleshed out example file to get you started on creating your own programming language.