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 🙂

Advertisements

About Wondering Bear
39 years old male bear.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: