Skip to content

Instantly share code, notes, and snippets.

@jokea
Created June 20, 2012 02:36
Show Gist options
  • Save jokea/2957827 to your computer and use it in GitHub Desktop.
Save jokea/2957827 to your computer and use it in GitHub Desktop.
[2/2] Erlang programming ex3_10
-module(ex3_10).
-export([format_pretty/2]).
format_pretty(Text, Width) -> do_format(Text, Width, Width).
do_format([], _, _) -> ok;
do_format([H | T], Width, 0) -> display_long_word([H | T], Width, []);
do_format(Text, Width, Request) ->
Len = length(Text),
if
Len < Width -> io:format("~p~n", [Text]);
true ->
Head = lists:sublist(Text, Request),
Last = lists:last(Head),
Remain = lists:sublist(Text, Request+1, Len-Request),
Next = lists:nth(1, Remain),
case [Last] of
" " -> format_fixed(lists:sublist(Head, length(Head)-1), Width),
do_format(Remain, Width, Width);
_ ->
case [Next] of
" " -> format_fixed(Head, Width),
do_format(lists:sublist(Remain, 2, length(Remain)-1), Width, Width);
_ -> do_format(Text, Width, Request-1)
end
end
end.
display_long_word([H | T], Width, R) when [H] /= " " ->
NewR = lists:append(R, [H]),
display_long_word(T, Width, NewR);
display_long_word(List, Width, R) ->
io:format("~p~n", [R]),
do_format(lists:sublist(List, 2, length(List)-1), Width, Width).
format_fixed(List, Width) ->
Len = length(List),
Fills = Width - Len,
if
Fills > 0 ->
NewList = add_blanks(List, Fills, []),
io:format("~p~n", [NewList]);
true ->
io:format("~p~n", [List])
end.
add_blanks(List, 0, Result) -> lists:append(Result, List);
add_blanks([], Fills, Result) when Fills > 0 -> add_blanks(Result, Fills, []);
add_blanks([H | T], Fills, Result) when [H] == " " ->
R1 = lists:append(Result, [H]),
R2 = lists:append(R1, [H]),
add_blanks(T, Fills-1, R2);
add_blanks([H | T], Fills, Result) ->
R1 = lists:append(Result, [H]),
add_blanks(T, Fills, R1).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment