1 ! Copyright (c) 2012 Anonymous
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: io kernel math math.functions sequences splitting strings ;
4 IN: rosetta.align-columns
6 ! http://rosettacode.org/wiki/Align_columns
8 ! Given a text file of many lines, where fields within a line
9 ! are delineated by a single 'dollar' character, write a program
10 ! that aligns each column of fields by ensuring that words in each
11 ! column are separated by at least one space. Further, allow for
12 ! each word in a column to be either left justified, right
13 ! justified, or center justified within its column.
15 ! Use the following text to test your programs:
17 ! Given$a$text$file$of$many$lines,$where$fields$within$a$line$
18 ! are$delineated$by$a$single$'dollar'$character,$write$a$program
19 ! that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
20 ! column$are$separated$by$at$least$one$space.
21 ! Further,$allow$for$each$word$in$a$column$to$be$either$left$
22 ! justified,$right$justified,$or$center$justified$within$its$column.
26 ! * The example input texts lines may, or may not, have trailing
28 ! * All columns should share the same alignment.
29 ! * Consecutive space characters produced adjacent to the end of
30 ! lines are insignificant for the purposes of the task.
31 ! * Output text will be viewed in a mono-spaced font on a plain
32 ! text editor or basic terminal.
33 ! * The minimum space between columns should be computed from
34 ! the text and not hard-coded.
35 ! * It is not a requirement to add separating characters between
38 CONSTANT: example-text "Given$a$text$file$of$many$lines,$where$fields$within$a$line$
39 are$delineated$by$a$single$'dollar'$character,$write$a$program
40 that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
41 column$are$separated$by$at$least$one$space.
42 Further,$allow$for$each$word$in$a$column$to$be$either$left$
43 justified,$right$justified,$or$center$justified$within$its$column."
45 : split-and-pad ( text -- lines )
46 split-lines [ "$" split harvest ] map
48 '[ _ "" pad-tail ] map ;
50 : column-widths ( columns -- widths )
51 [ longest length ] map ;
53 SINGLETONS: +left+ +middle+ +right+ ;
55 GENERIC: align-string ( str n alignment -- str' )
57 M: +left+ align-string drop CHAR: space pad-tail ;
58 M: +right+ align-string drop CHAR: space pad-head ;
60 M: +middle+ align-string
63 [ floor CHAR: space <string> ]
64 [ ceiling CHAR: space <string> ] bi surround ;
66 : align-columns ( columns alignment -- columns' )
67 [ dup column-widths ] dip '[
68 [ _ align-string ] curry map
71 : print-aligned ( text alignment -- )
72 [ split-and-pad flip ] dip align-columns flip
73 [ [ write bl ] each nl ] each ;
75 ! USAGE: example-text +left+ print-aligned