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 :)

Sinatra: using partials with xml builder

After working mostly with Java for last few years I am back to using Ruby as a main language for my every day work. I have to say just thinking of that makes me smile :). We use Sinatra to cover our web needs and I love it.
Recently I had to generate some outbound xml feeds and wanted to reuse builder templates. Following is my take on a builder partial implementation :

module Sinatra
  module BuilderHelper
    def helper_modules
      @helper_mods ||= Sinatra::Application.ancestors.select{|m| m.name =~ /Helper/}
    end

    def builder_partial(template, xml, locals = {}, helper_mods = nil)
      template = "#{template}.builder" unless "#{template}" =~ /[.]builder$/
      helper_mods ||= self.helper_modules

      class << (context = OpenStruct.new({:xml => xml}.merge(locals))); self; end.send(:include, *helper_mods)

      File.open(File.join(settings.views, "#{template}")) do |f|
        eval f.read, context.send(:binding)
      end
    end
  end

  helpers BuilderHelper
end

As you can see, I am using OpenStruct as a context object in order to limit variable scope to the locals being passed to the partial… If you use other Sinatra helper modules and follow a naming convention, helper_mod will find it and make them available to the builder template…
This is a pretty simple helper module… but I am hoping it will save somebody time.

JQuery: Collect input data

Working on a simple data entry app I’ve ran into a need to collect data from multiple rows of input fields in order to post json data back to the server. Following is a simple jquery plugin, that in combination with few extra html attributes allows to collect data and convert it into json:

(function( $ ){
  $.fn.collectFields = function(fieldSelector) {
	var convert = function(type, value) {
		switch (type) {
			case "int"     : return value ? parseInt(value) : 0;
			case "float"   : return value ? parseFloat(value): 0.0;
			case "boolean" : return Boolean(value);
			default        : return value;	
		}
	};

	var result = [];
	this.each(function() {
	  	var fields = {};
		$(this).find(fieldSelector).each(function(){
			var name = $(this).attr('name');
			if (name) {
				fields[name] = convert($(this).attr("json-type"), $(this).val());
			}
		});
		result.push(fields);
	});
	return result;

  };  
})( jQuery );

As you can see, I am using “json-type” attribute to indicate a type of the data field. In html it looks something like the following:


<tr class="player">
  <td><input type="hidden" id="id__5" name="_id" value="5" class="field" /></td>
  <td><input type="text" id="number__5" name="number" value="23" class="field" json-type="int"/></td>
  <td><input type="text" id="name__5" name="name" value="Some Good Player" class="field"/></td>
</tr>
...

Script to collect data for all players would look something like this:

<script>
  var players = $(".player").collectFields(".field");
</script>

Discovering Python

Despite my strong bias towards Ruby, I am finally learning Python.
I think functional nature of the Python is what makes it attractive to me. After spending a lot of time with Erlang and Ruby, I found Python to be an interesting hybrid.. kind of “in between” Ruby magic and pure functional feel of Erlang. I like the fact that pretty much all Ruby meta programming is still possible and on top of that Python has a very good support for functions, higher level functions, which makes is very interesting combination for me. For a few years now I’ve been hearing people talking about it, but it did not register with me until I started playing with it. One thing for sure I am going to put more time into it…

Functional Example (very Erlangish and Rubyish in the same time :) )

In [21]: def wrapper(fun):
      ....:   def func(*args, **kwargs):
      ....:     print " begin execution %s " % (fun.__name__)
      ....:     fun(*args, **kwargs)
      ....:     print " finished execution %s " % (fun.__name__)
      ....:   return func
      ....: 

In [22]: def hello(msg):
      ....:   print "hello %s" % (msg)
      ....: 

In [23]: f = wrapper(hello)

In [24]: f("Alex")
 begin execution hello 
 hello Alex
 finished execution hello 

Sinatra request headers helper

It is pretty simple, but here is an example of getting request headers from the Rack Environment in a Sinatra application :

require 'rubygems'
require 'sinatra'

helpers do
  def request_headers
    env.inject({}){|acc, (k,v)| acc[$1.downcase] = v if k =~ /^http_(.*)/i; acc}
  end  
end

get '/headers' do
  puts request_headers.inspect
 end

request_headers helper will filter all HTTP headers and downcase names.

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 :)

Follow

Get every new post delivered to your Inbox.