Created
June 19, 2012 10:23
-
-
Save jokea/2953413 to your computer and use it in GitHub Desktop.
[1/2] Erlang programming ex3_10
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-module(ex3_10). | |
-export([format/2]). | |
format(Text, Width) -> do_format(Text, Width, Width). | |
do_format([], _, _) -> ok; | |
do_format(Text, _, Width) when length(Text) < Width -> io:format("~p~n", [Text]); | |
do_format([H | T], Width, 0) -> display_long_word([H | T], Width, []); | |
do_format(Text, Width, Request) -> | |
Len = length(Text), | |
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 | |
" " -> io:format("~p~n", [lists:sublist(Head, length(Head)-1)]), | |
do_format(Remain, Width, Width); | |
_ -> | |
case [Next] of | |
" " -> io:format("~p~n", [Head]), | |
do_format(lists:sublist(Remain, 2, length(Remain)-1), Width, Width); | |
_ -> do_format(Text, Width, Request-1) | |
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). | |
%%% test input: | |
ex3_10:format("Write a function that will print this in a readable form, so that duplicates are removed and adjacent numbers are put into a range. You might like to think of doing this via a function which turns the earlier list of occurrences into a list like [{1,2},{4,6},{98,98},{100,100},{102,102}] through a sequence of transformations.", 30). |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment