Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -module(format).
- -export([fixed_line_length/2]).
- %
- % In word processing systems it is customary for lines to be filled
- % and broken automatically, to enhance the appearance of the text.
- % Input of the form
- %
- % The heat bloomed in December
- % as the carnival season
- % kicked into gear.
- % Nearly helpless with sun and glare, I avoided Rio's brilliant
- % sidewalks
- % and glittering beaches,
- % panting in dark corners
- % and waiting out the inverted southern summer.
- %
- % would be transformed by filling to
- %
- % The heat bloomed in December as the
- % carnival season kicked into gear.
- % Nearly helpless with sun and glare,
- % I avoided Rio's brilliant sidewalks
- % and glittering beaches, panting in
- % dark corners and waiting out the
- % inverted southern summer.
- %
- % Loads a file and returns each of its
- % lines (list of strings) with a constant maximum length
- fixed_line_length(FileName, Length) ->
- Words = words_from_file(FileName),
- ExistWordsLongerThanLength = lists:any(fun(WordI) -> length(WordI) + 1 > Length end, Words),
- if
- ExistWordsLongerThanLength ->
- throw("There are some words longer than maximum line length");
- true ->
- format_words_in_fixed_line_length(Words, Length)
- end.
- % Split lines in fixed length
- format_words_in_fixed_line_length([WordI|Words], Length) ->
- format_words_in_fixed_line_length(Words, Length, "", WordI).
- format_words_in_fixed_line_length([], _, Acc, CurrLine) -> Acc ++ [CurrLine];
- format_words_in_fixed_line_length([WordI|Words], Length, Acc, CurrLine) ->
- CurrLineLength = length(CurrLine),
- WordILength = length(WordI),
- if
- CurrLineLength + WordILength + 1 > Length ->
- format_words_in_fixed_line_length([WordI|Words], Length, Acc ++ [CurrLine], "");
- true ->
- format_words_in_fixed_line_length(Words, Length, Acc, string:trim(CurrLine ++ " " ++ WordI))
- end.
- % Return a list with a words from the file named FileName.
- words_from_file(FileName) ->
- FileLines = get_file_contents(FileName),
- Words = lists:concat(
- lists:map(
- fun(FileLine) -> string:tokens(FileLine, " ") end,
- FileLines
- )
- ),
- Words.
- % Get the contents of a text file into a list of lines.
- % Each line has its trailing newline removed.
- get_file_contents(Name) ->
- {ok,File} = file:open(Name,[read]),
- Rev = get_all_lines(File,[]),
- lists:reverse(Rev).
- % Auxiliary function for get_file_contents.
- % Not exported.
- get_all_lines(File,Partial) ->
- case io:get_line(File,"") of
- eof -> file:close(File),
- Partial;
- Line -> {Strip,_} = lists:split(length(Line)-1,Line),
- get_all_lines(File,[Strip|Partial])
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement