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