Sunday, March 9, 2008

Directories Recursively and Simple Binary Matching

Hi, It has been a long time :)

So today two simple things first, some high order fun to work on tree:

-module(dir).
-export([create/1]).

create(List) ->
H = fun(X) ->
fun(Y) ->
Dir = filename:join([X,Y]),
io:format("mkdir(~s)~n", [Dir]),
Dir
end
end,
build(fun(X) -> X end, H, List).

build(_Fun, _Builder, []) ->
ok;
build(Fun, Builder, [Elem|List]) ->
NewFun = Builder(Fun(Elem)),
build(NewFun, Builder, List).


A sample session:

5> dir:create(["ab","cd", "ef","12", "35", "av"]).
mkdir(ab/cd)
mkdir(ab/cd/ef)
mkdir(ab/cd/ef/12)
mkdir(ab/cd/ef/12/35)
mkdir(ab/cd/ef/12/35/av)
ok

What's interesting is the Builder fun that construct the fun that will be called the next time.
That way we know were we are in the tree... The last Fun has all the knowledge of its ancestors :)

Now a simple binary matcher code, I need it while extracting values from regex results. It takes a list of offsets and returns what's inside:

slice(Slices, Bin) ->
slice(Slices, [], Bin).

slice([], Acc, _Bin) ->
lists:reverse(Acc);
slice([ {Start, Stop} | Rest ], Acc, Bin) ->
Len = Stop - Start,
<<_:Start/binary,Value:Len/binary,_/binary>> = Bin,
slice(Rest, [ Value | Acc ], Bin).


A sample session:

8> matcher:slice([{1,5},{8,10}], <<"this is a not a solution">>).
[<<"his ">>,<<"a ">>]


I hope that someone will find this valuable...

2 comments:

Anonymous said...
This comment has been removed by a blog administrator.
gongfermor said...

Hi!

This blog is great! It's a great resource for someone just starting out with Erlang and I hope you keep it up!

Cheers
Eric

Sticky