Prime numbers with Erlang

I was helping my son with math homework today.. One of the problems was to find all prime numbers up to a 100.. That was enough for me to start looking for an old Erlang script I have played with few years ago…

-module(eratosthenes).
-export([prime_numbers/1]).

% Sieve of Eratosthenes algorithm for finding all prime numbers up to N.
% http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes

% Generate list of prime numbers up to N.
prime_numbers(N) when is_number(N) ->
prime_numbers(N, generate(N)).

prime_numbers(Max, [H|T]) when H * H =< Max ->
   [H | prime_numbers(Max, [R || R <- T, (R rem H) > 0])];

prime_numbers(_, T) -> T.

% Generate sequence 2..N
generate(N) -> generate(N, 2).

generate(Max, Max) -> [Max];

generate(Max, X) -> [X | generate(Max, X + 1)].

What can I say… Love Erlang 🙂

Easy Mocking in Erlang

Working on yarmo and trying to do test driven development I ran into need to mock some modules to avoid need for hitting database every time. After a bit of trying and errors I ended up using pretty simple set up based on parametrized modules. Basic idea is to pass a proplist, with mock responses for methods I am trying to mock, into the module as module parameter and have methods look it up:

-module(mock_store, [MockStore]).
-export([read/1, create/1]).

read(Key) ->
	callback(read, [Key]).

create(Key, Document) ->
	callback(create, [Key, Document]).

%% Helper Functions

callback(Name, Args) ->
	case proplists:lookup(Name, MockStore) of
		none -> undefined;
		{Name, Fun} when is_function(Fun) -> Fun(Args);
		{Name, Value} -> Value
	end.

The callback is pretty simple, but allows to pass in ether mock result or a function, which will generate response based on parameters, passed to the method.
Now I can mock read/create in the test as following:

test_mod(StoreOptions) ->
	Store = mock_store:new(StoreOptions),
	yarmo_destination:new(Store).

....

Mod = test_mod([{read, not_found}]),
.....

Mod = test_mod([{read, fun([Key]) -> ?assertEqual("sample", Key), Doc end}])

Nothing special, but so far it is helping me to keep my tests from hitting real storage 🙂

YARMO – Yet Another RESTFul Messaging Option

I’ve been spending a lot of time in a past few month doing research around a “RESTful” messaging solution. The idea is to have a web service that can support queue and topic notations and provide more less simple REST based API. What I found so far is that there is no good “out of the box” implementation. There is a specification REST-*, that looks very promising in my opinion… So, I’ve decided it would be fun to try implementing this spec. Since I am still a big fan of Erlang, I will be using it for the project. So far it is shaping up to be a MochiWeb application with CouchDB used for storage. It is still very much work in progress, but for now it is my new Erlang playground 🙂

More fun with Erlang

I am working on a prototype of an application that needs to proxy client HTTP requests to different origins. I needed a function that will filter HTTP headers before I forward them. Application is in Erlang, but since I’ve been a big Ruby fan for a while now… Here is a comparison of possible implementations:

Ruby:

  NO_FORWARD = ['Host', 'Content-Length', 'Accept-Encoding']
  
  def filter_headers(headers)
      headers.inject({}) do |result, (name, value)|
         result[name.to_s] = value unless NO_FORWARD.include?(name.to_s)
         result
      end
  end

Now, same code … but in Erlang:


filter_headers(Headers) ->
NoForward = ['Host', 'Content-Length', 'Accept-Encoding'],

Pred = fun({Name, Value}, L) ->
case lists:member(Name, NoForward) of
false ->
Key = case is_atom(Name) of
true -> atom_to_list(Name);
false -> Name
end,
[{Key, Value} | L];
true -> L
end
end,

lists:foldl(Pred, [], Headers).

I think given a bit more effort, each code sample might be even more compact, but even what I have looks pretty readable 🙂

Erlang – elegant, but mind blowing :)

I’ve been playing around with Erlang for a while now. Interesting thing about Erlang is that the language is pretty small and very consistent, I guess it is typical for functional language 🙂 , but in a same time it takes a long time to start thinking in “Erlang way”. Everything is based on pattern matching – function signatures, case and if statements are all just pattern matching. Once you get a hold of it… it is a lot of fun and makes code pretty clean, short and readable.
Here is an example of function that parses ttl – 20s, 10m, 2h :

first we have an entry point:


parse(Ttl) -> parse_ttl(lists:reverse(Ttl)).

And here comes all the fun :


%% Private Functions.

parse_ttl([$s | Ttl]) -> list_to_integer(lists:reverse(Ttl));
parse_ttl([$S | Ttl]) -> parse_ttl([$s | Ttl]);

parse_ttl([$m | Ttl]) -> 60 * list_to_integer(lists:reverse(Ttl));
parse_ttl([$M | Ttl]) -> parse_ttl([$m | Ttl]);

parse_ttl([$h | Ttl]) -> 60* 60 * list_to_integer(lists:reverse(Ttl));
parse_ttl([$H | Ttl]) -> parse_ttl([$h | Ttl]);

parse_ttl(_) -> false.

Since strings in Erlang are just lists of integers, it is very common to apply list functions to strings. The [H | T] notation allows you to separate “head” and a “tail” of the list; in our case first symbol and the rest of the string. And since we have reversed our original string before applying our pattern … it is working pretty well 🙂