Benjamin Halsted // [bgh] todo, add something clever here.

18Mar/100

Erlang Programming Exercise: 3-5 (refactor)

I wasn't happy with how the flatten and concatenate functions turned out. They weren't taking advantage of tail call optimizations, so I rewrote the flatten function for fun. During my rewrite I also wanted to avoid using BIFs to work on my pattern matching. I wasn't sure if I would be able to match the head of a list, that was the head of a list. It worked out, here is the result:

flattenHelper(Dst, []) ->
        Dst;
flattenHelper(Dst, [[[]|HeadTail]|T]) ->
        flattenHelper(Dst, [HeadTail|T]);
flattenHelper(Dst, [[HeadTop|HeadTail]|T]) ->
        NewList1 = [HeadTail|T],
        NewList2 = [HeadTop|NewList1],
        flattenHelper(Dst, NewList2);
flattenHelper(Dst, [[]|T]) ->
        flattenHelper(Dst, T);
flattenHelper(Dst, [H|T]) ->
        flattenHelper([H|Dst], T);
flattenHelper(Dst, Item) ->
        [Item|Dst].

flatten(Lists) ->
        reverse(flattenHelper([], Lists)).

Cheers,
-Halzy

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • Reddit
  • Twitter
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.