May 28th, 2009

Notepad-Plus-Plus Plus Erlang

My primary dev environment is Windows, my main IDE is Eclipse or Aptana (leaning slightly towards Aptana’s flavour of Eclipse lately, especially for PHP and Ruby on Rails), and for quick code edits, messing about and text editing I use Notepad++.

Notepad++ has served me well over the years: it’s free, loads up fast (unlike the big IDEs) and gets the job done. I know that there are quite a few alternatives (In Type looks particularly appealing), but NP++ does what I need nicely.

However, I was quite surprised and disappointed that there was no inbuilt support for my new favourite language: Erlang! A quick Google around revealed that I’d have to add a user defined language to my installation, less quick was tracking down an example file for Erlang. I eventually discovered this old mailing list post. I then built my own variation that suites dark backgrounds, you can download it below.

To install you will need to replace or merge with the *path-to-AppData*/Notepad++/userDefineLang.xml

file. If you don’t use a dark background alter the WordStyle tag properties: fgColor and bgColor to suit.

Download the userDefinedLang.xml

Let me know if you know of any better versions or edits, I’m sure mine is incomplete.

May 27th, 2009

Hear my voice (on the Guardian Tech PodCast)

Last Friday I went along to the Guardian Tech Weekly Tour’s visit to Bristol (in case you didn’t know I mostly grew up and now live in Bristol).

I thought it’d be a good chance to meet up with a few faces from the local start-ups and web-development scene. So, I was pleasantly supprised to be able to have a chat with Jemima Kiss and get a bit of advice/insight into the projects I’m working on, I assumed that she’d be mobbed and too busy. She gave some really constructive and positive feedback on the web apps I’m building; it was a pleasant end to the week.

While there I was also interviewed for the podcast about what makes Bristol a good location for web development and starting a business (not that I know a great deal about the latter). I was slightly drunk on one and a half pints (it happens that way sometimes) so didn’t expect to make it into the show… But, I did – so if you want to hear my weird high-pitched voice listen to Tech Weekly: On the road in Bristol (I pop up at 22:38).

PS: If you’re bored of posts about my day-to-day existence: fear not, there’s some solid programming fun coming up later this week…

May 22nd, 2009

This week’s fun

No big post this week, due to being pretty busy, so instead I’ll round up some of the bits and pieces that have occupied my mind this week.

Erlang:

On the Erlang front I’m wading through some slightly less blog-worthy chapters of Programming Erlang: Software for a Concurrent World, getting to grips with error handling and exeptions. I’m going to try and tackle a more unusual task next week.

At work:

I’ve been wresteling with Servers. One site is flat HTML, and should therefore run super fast – however, due to a huge quantity of internal redirects and a sudden upsurge in traffic the server was grinding to a halt! Solution: move the redirects from .htaccess files over to vhost.conf, but I think they are going to have to be whittled down very soon.

I also set up a CentOS Virtual Machine as a staging/testing environment and was pretty pleased by how much I can get done from memory using the shell. It’s a while since I realy played with Linux for more than a couple of hours and I could definitely envisage moving over to it on a more permanent basis. Quite a few dev tasks are easier there.

Personal Projects:

Development on my second web app (the first being Good Baad) is coming together nicely. The working prototype is built with my “ultra-lightweight” PHP MVC framework, which I’ll write about some time soon. Although I’m wondering about porting to Erlang as it’s a heavily realtime system that could take advantage of Erlang’s concurrency.

Random Thought:

I’ve been worrying about the environmental impact of the web, and most discussions focus on the huge server farms used by mega-sites like Google and Facebook. However, I’m sure that individual developers and small companies could be working more actively on these problems too.

What a dull post! I’ll step it up next time, promise. Just to spice things up here’s a video of a nutty robot:

May 14th, 2009

Erlang FizzBuzz Showdown (pt2)

In my last post I documented some of the steps involved in building a simple FizzBuzz script in Erlang and compared the code to its equivalents in Python, Ruby and PHP. So far we’ve simply covered using a tail-recursive function to creat a list of numbers 1-100.

The next problem to tackle is checking whether a number is: just a number, a Fizz (divisible by 3), a Buzz (divisible by 5) or a FizzBuzz (divisible by 3 and 5). As I’m in the habit of using if statements to perform checks (I’m primarily a PHP developer) my first attempt looked like this:

fizzbuzz(I) ->
    if
        ((I rem 3 =:= 0 ) and (I rem 5 =:= 0 )) ->
            fizzbuzz;
        I rem 3 =:= 0 ->
            fizz;
        I rem 5 =:= 0 ->
            buzz;
        true ->
            I
    end.

This works just fine, but isn’t a good example of writing Erlang in a functional manner, this is more like imperative programming in style. For example, it is not dissimilar to this python function:

# python

def fizzbuzz(i):
  if i % 3 == 0 and i % 5 == 0:
    return 'Fizzbuzz'

  elif i % 3 == 0:
    return 'Fizz'

  elif i % 5 == 0:
    return 'Buzz'

  else:
    return i

In Erlang (and I assume functional programming in general) Guards rather than if statements are far more appropriate. So, using the multiple entry points for a function and combining them with a guard I ended up with this:

fizzbuzz(N) when N rem 3 == 0, N rem 5 == 0 -> "FizzBuzz";
fizzbuzz(N) when N rem 3 == 0 -> "Fizz";
fizzbuzz(N) when N rem 5 == 0 -> "Buzz";
fizzbuzz(N) -> N.

Once I’d taken on board the functional approach the FizzBuzz function has not lost any readability (if anything this is easier to follow) and has become more compact and efficient. From what I’ve seen so far: Erlang programs rarely need if statements.

The next stage in the FizzBuzz program is to combine this with my earlier range function and loop through the numbers 1-100. Attempt 1 worked like so:

combine(To) ->
  F = (fun(I) ->  fizzbuzz(I) end),
  lists:map(F,range(1,To,[])).

Again, this works: the function combine takes in the number to be counted up to (e.g. 100), then a Fun is created (basically a mini function that can be passed into other functions as an argument) that is a copy of fizzbuzz, and then uses the inbuilt module/function lists/map to apply it to each number in the list returning a new list with the appropriate changes. But again this can be condensed to make better use of Elang’s functional syntax.

combine(To) ->
  [fizzbuzz(X) || X <- range(1,To,[])].

The end result is the same but the function now uses a pattern matching/balancing style syntax to produce the new list. The process breaks down like this:

  • [] is the list notation, and using the pipes to separate the two haves of the process ([X || X <- [1,2,3,4]]) means that the result of the right hand site is passed into the left (as X, formed by breaking the list down X <- [1,2,3,4]), forming a new list one element at a time.
  • The input list is formed using the range function on the right.
  • Then the fizzbuzz function processes the incoming elements of the new list on the left.

And that almost concludes my Erlang FizzBuzz program. However, it is returning a list rather than printing one line at a time. This is the module so far:

-module(fizzbuzz).
-export([fizzbuzz/1,range/3,combine/1]).

fizzbuzz(N) when N rem 3 == 0, N rem 5 == 0 -> "FizzBuzz";
fizzbuzz(N) when N rem 3 == 0 -> "Fizz";
fizzbuzz(N) when N rem 5 == 0 -> "Buzz";
fizzbuzz(N) -> N.

range(To,To,List) -> [To|List];
range(From,To,List) when From < To -> range(From, To -1, [To|List]);
range(From,To,List) when From > To -> List.

combine(To) ->
  [fizzbuzz(X) || X <- range(1,To,[])].

And being used in the console:

Eshell V5.6.5  (abort with ^G)
1> c(fizzbuzz).
{ok,fizzbuzz}
2> fizzbuzz:combine(100).
[1,2,"Fizz",4,"Buzz","Fizz",7,8,"Fizz","Buzz",11,"Fizz",13,
 14,"FizzBuzz",16,17,"Fizz",19,"Buzz","Fizz",22,23,"Fizz",
 "Buzz",26,"Fizz",28,29|...]

Finally, this can be condensed one last time by turning the range function into a tool for applying the fizzbuzz function to each number recursively, printing the results to the console as it goes:

-module(fb_final).
-export([fizzbuzz/1,fbr/2]).

fizzbuzz(N) when N rem 3 == 0, N rem 5 == 0 ->
  io:format("FizzBuzz\n");

fizzbuzz(N) when N rem 3 == 0 ->
  io:format("Fizz\n");

fizzbuzz(N) when N rem 5 == 0 ->
  io:format("Buzz\n");

fizzbuzz(N) ->
  io:format([integer_to_list(N) | "\n"]).

fbr(To,To) -> fizzbuzz(To);
fbr(From,To) when From < To -> fizzbuzz(From), fbr(From + 1, To).

And with that I’m pretty pleased. The fb_final module makes good use of the functional approach, is concise but still fairly easy to read. In conclusion I’m enjoying Erlang a great deal.

P.S:

There is one last small modification that makes fbr/range reusable allowing higher order functions to be passed into it:

range(To,To,F) -> F(To);
range(From,To,F) when From < To -> F(From), range(From + 1, To,F).

This executes using the following console script (inserting fizzbuzz into range as a higher order function):

Eshell V5.6.5  (abort with ^G)
1> c(fb_final).
{ok,fb_final}
2> fb_final:range(1,15,fun(N) -> fb_final:fizzbuzz(N) end).
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
ok

Done and dusted! And here are some other ways of getting FizzBuzz done in a functional style.

May 13th, 2009

Erlang FizzBuzz Showdown (Pt 1)

As I’ve become a little more familiar with Erlang I decided to leave the set text and test myself with a basic (often seen) programming challenge (FizzBuzz) and compare the solution with the languages I’m more familiar with.

FizzBuzz is a pretty simple set of rules (also known as Bizz Buzz) and is used for children’s maths, drinking games and as a rather basic test given to programmers during job interviews (although it is so well known that it probably lost its value for this purpose a while back).

The rules (for programmers) are simple:

  • Print a list of numbers 1 – 100
  • If the number is exactly divisible by 3 print “Fizz”
  • If the number is exactly divisible by 5 print “Buzz”
  • If the number is exactly divisible by both 3 and 5 print “FizzBuzz”
  • Otherwise just print the number

Solving the problem breaks down to:

  • Create a range of numbers 1-100
  • Loop through each number and check it against the conditions
  • Print out the result
  • Repeat until 100

So far so simple, it is a pretty straight forward task that can be solved in a broad variety of ways.

Here’s how I could achieve this in Python:

for i in range(1,101):

  if i % 3 == 0 and i % 5 == 0:
    print 'Fizzbuzz'

  elif i % 3 == 0:
    print 'Fizz'

  elif i % 5 == 0:
    print 'Buzz'

  else:
    print i

And PHP:

foreach (range(1,100) as $i)
{
    if (($i % 5 == 0) && ($i % 3 == 0))
    {
        echo "FizzBuzz\n";
    }
    elseif ($i % 3 == 0)
    {
        echo "Fizz\n";
    }
    elseif ($i % 5 == 0)
    {
        echo "Buzz\n";
    }
    else
    {
        echo "$i\n";
    }
}

Of course there are many variations depending on how short and/or “readable” you’d like it to be.

So, when it came to tackling this problem with Erlang I was a little surprised that I couldn’t just launch into it. Approaching this problem functionally is a different kettle of fish. While there are built in functions that can help I chose to ignore them in favour of gaining a little more understanding.

In other languages creating a range of numbers was pretty straight forward and barley registered as a task, in Erlang I needed to think a little harder. There is no for or while loop easily to hand, the solution was a tail-recursive function. It might seem bloated to add this function, but if you compare the same function in Ruby, the Erlang function appears better suited to the task (also using tail recursion in none functional languages causes performance/stack issues so this is more for illustration):

% ERLANG

range(To,To,List) -> List ++ [To];
range(From,To,List) when From < To -> range(From + 1, To, List ++ [From]).
#RUBY

def jRange(from,to,list)
  if from == to
    return list << from
  else
    list << from
    return jRange(from+1,to,list)
  end
end

Erlang functions can have multiple entry points, so in this case the range function has two entry points:

  • One that accepts two identical values, a list and returns a list with the value added.
  • Another that accepts two different values, a list and adds the first value to the list, then calls the same function (itself) adding one to the first value.

As it matches the incoming conditions there is no need for if or else.

The problem with this loop is that it will go on infinitely if From is greater than To, to cover this we need a guard. This is a simple check that From is less than To:

range(To,To,List) -> [To|List];
range(From,To,List) when From < To -> range(From, To -1, [To|List]).

And now we have an operational "range" function similar to those seen in Python, Ruby and PHP - however, Elang FizzBuzz can use it in various different ways. Another small change was to alter the way the list builds up, using List ++ [From] isn't very efficient and [To|List] does the job more elegantly.

In the next post I'll conclude building a FizzBuzz program (mistakes, solutions and better-practice included), check back tomorrow or subscribe to keep up to date.

Part 2 >>

May 11th, 2009

Learning Erlang: Intro

Learning Erlang: Week One

It’s a little over a week since I started working through Programming Erlang and it has been a very pleasurable/rewarding few days.

I like to learn new languages for a number of reasons, including: adding skills to my repertoire and gaining new perspectives on my other programming techniques and languages. Despite only being able to grab a half hour here and there I feel these aims have already been achieved in some measure, and it had certainly given me an appetite to learn a lot more. My advice to any developer looking to experience functional languages for the first time is: pick a language (Haskell, Lisp, Scala etc…) and just give it a try. I’m sure some will end up being the more widely adopted than others, but as a learning experience all will be rewarding.

So, as a PHP developer with experience of other Object Oriented and Scripting Languages (Ruby, Python, ECMA etc…) the transition has been interesting to say the least. The key differences when programming in a functional language are the similarities to writing algebra (something I haven’t thought seriously about since maths lessons aged 16).

These differences are down to:

  • variables can be set only once
  • the equals symbol is used for pattern matching rather than setting
1> X = 10.
10
2> X = 5.
** exception error: no match of right hand side value 5
3> 5+5 = X.
10
4> X = 2*5.
10

As you can see from the Erlang Console (above periods/full-stops terminate an instruction), as long as both sides of the equals equate to the same result, the program succeeds, I suppose = is used to set X in the first place but from there onwards it’s matching/balancing the two sides – as it would in maths.

Combining balancing/pattern-matching with unchangeable variables (variables that don’t vary if you like) is a method of preventing/reducing the opportunity for broken code. For example:

1> X = 100.
100
2> Y = X * 2.
200

The statement Y = X * 2. means that Y always equates to 200 as long as X is 100, if you could change X that statement would break. However, you can’t change X so in this case Y = X * 2. will always be 200!

This is a very basic observation and one of the smallest hurdles in making the transition from OOP to functional programming, but if you have never seen it before it represents a fairly significant change to the norm.

There are plenty of other changes to adjust to such as: code isn’t separated into Classes and Methods, but instead Erlang uses Modules and Functions (Modules are essentially containers for function groups) but these don’t produce objects. Something I’m yet to get used to. I’m not yet far enough along to see how complex chunks of information/functionality are handled. A more thorough introduction can be found in the first couple of chapters of Getting Started With Erlang.

This post is just about giving the briefest taste of what Erlang and Functional Programming are like to use, and hopefully encourage others to investigate a little further. In my next post I’m going to run through a simple task I set myself and completed last week: FizzBuzz (as noted by Jeff Atwood as a simple test of programming competence), and give some comparisons to PHP, Python and Ruby.

May 8th, 2009

Erlang White Paper

This is just a short post to point potential Erlang-ers to the Erlang –White Paper.

It acts as a really concise overview of the language, its purposes and illustrates how to use it. I’m thinking that it will act as a quick reference while learning as it covers most of the basics principals (on first glance it may be enough to get most programs underway).

A roundup of my first week of Erlang is on its way soon, this taster shows how to create a list containing a range of numbers (there is a built in equivalent and it isn’t particularly impressive – but it’s neat and pleases me).

range(To,To,List) -> List ++ [To];
range(From,To,List) -> range(From + 1, To, List ++ [From]).

May 6th, 2009

A random/cool Erlang video from way back!

May 5th, 2009

First Post O’clock!

As this blog is something of a stream of consciousness I thought it might be useful to lay out the themes that I’ll be touching on over the next few posts.

First and foremost, I’m a working developer producing PHP sites for S-cool and that is how I earn my living. I’m not: claiming to be a “rock star” programmer, aiming to blow my own trumpet or otherwise puff up my own ego. The more modest intention is to document the problems and solutions that I find interesting/exciting and hopefully engage in, and contribute to, the various developer communities a little more.

Core areas of interest are:

  • writing efficient, beautiful, scalable code
  • comparing/discussing the various languages, frameworks, tools and ideologies
  • learning new skills

The language I’ve most recently adopted is Erlang and I expect the majority of my first posts will cover my progress learning how to use it and evaluating why functional programming is so hot right now. If you are interested in joining in, learning along or setting me straight when I misunderstand: my current guides are The Getting Started With Erlang and Programming Erlang: Software for a Concurrent World.

Powered by Wordpress using the theme aav1