Align columns: Difference between revisions

Content added Content deleted
No edit summary
(shiny example)
Line 2,557: Line 2,557:
val padded = words map ( _.zipWithIndex.map{case(s,i)=>pad(s,maxlens(i),"center")+" "} )
val padded = words map ( _.zipWithIndex.map{case(s,i)=>pad(s,maxlens(i),"center")+" "} )
padded map (_.reduceLeft(_ + _)) foreach println</lang>
padded map (_.reduceLeft(_ + _)) foreach println</lang>

=={{header|Shiny}}==
<lang shiny>text: 'Given$a$text$file$of$many$lines,$where$fields$within$a$line$
are$delineated$by$a$single$\'dollar\'$character,$write$a$program
that$aligns$each$column$of$fields$by$ensuring$that$words$in$each$
column$are$separated$by$at$least$one$space.
Further,$allow$for$each$word$in$a$column$to$be$either$left$
justified,$right$justified,$or$center$justified$within$its$column.'

align: action text; position;

# split text into 2D array of lines and words
lines : { for text.split ~\$?\r?\n~ { for a.split '$' a end } end }

# calculate max required width for each column
widths: { for lines for a here[b]: a.length.max here[b]? ends }

spaces: action out ("%%%ds" in).format '' end

# formatting functions
left: action word; width;
pad: width-word.length
print "%s%s " word spaces pad
end
right: action word; width;
pad: width-word.length
print "%s%s " spaces pad word
end
center: action word; width;
pad: (width-word.length)/2
print "%s%s%s " spaces pad.floor word spaces pad.ceil
end

if position.match ~^(left|center|right)$~ for lines
for a local[position] a widths[b] end say ''
ends say ''
end

align text 'left'
align text 'center'
align text 'right'</lang>

<pre>Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.

Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.

Given a text file of many lines, where fields within a line
are delineated by a single 'dollar' character, write a program
that aligns each column of fields by ensuring that words in each
column are separated by at least one space.
Further, allow for each word in a column to be either left
justified, right justified, or center justified within its column.</pre>


=={{header|Tcl}}==
=={{header|Tcl}}==