Thursday, June 26, 2008

PE Problem #1 in Erlang

And now I finally get to Erlang. I actually wrote up the code this past weekend, but a few other things got in the way of this blog entry. I'm sure you were all waiting on pins and needles.

The Erlang Code

sum35(N) -> sum([X || X <- seq(0,N), interesting_number(X)]).
interesting_number(N) -> (N rem 3 == 0) or (N rem 5 == 0).

What surprised me the most was how much Erlang borrowed its syntax from Prolog. I had been alerted to this by a student who looked at the language for a programming languages course. I would have guessed that Erlang's syntax had been based more on Haskell (and Miranda and Clean).

As for the solution, it seems pretty straightforward with yet another list comprehension. I'm not sure if I like the || for the "such that" in the list comprehension, but that's fairly minor.

sum and seq come from the list library.

Problems with Erlang

The biggest problem I had with Erlang was getting a unit-testing library. My Erlang installation (from MacPorts) came with Erlang/OTP Test Server, but it's very, very heavyweight. eUnit, though, is very lightweight and very similar to the other xUnit libraries I've used. Unfortunately, it wasn't installed by default, and it took some time getting that right.

Otherwise, it was just the standard amount of time to figure out how to write and run the tests and command-line program.

What's Erlang good for?

Unfortunately, it's unlikely that the Project Euler problems will ever require me to use the distributed computing abilities of Erlang. It's still good to use Erlang for these problems so that I get practice with the syntax. (We'll see how long it takes me to change this tune!)

Next...

It's time to move on to Problem #2.

2 comments:

Brandon said...

Jeremey,

Joe Armstrong was using Prolog before writing Erlang, so he said that Erlang was heavily influenced by it.

As for unit testing, Joe said he doesn't actually use a library. Since Erlang does pattern matching for "assignment", and errors if the pattern doesn't match (much like an assertion), he just defines a "test" function along with his code that uses pattern matching to assert the return values.

Jeremy D. Frens said...

@brandon: that's an interesting take on testing. It now occurs to me that the unit tests I've written in Prolog work that same way.

There's something about using a standard xUnit library. Even Ruby's non-standard assert_equal (instead of assert_equals) is annoying enough. That'll probably be enough to keep me working with eUnit for now.