Align columns: Difference between revisions

Content added Content deleted
mNo edit summary
(add E example)
Line 396: Line 396:
(princ "~}~%~}" s))
(princ "~}~%~}" s))
fields))</lang>
fields))</lang>

=={{header|E}}==

<lang e>
pragma.enable("accumulator")

def left(width, word) {
return word + " " * (width - word.size())
}

def center(width, word) {
def leftCount := (width - word.size()) // 2
return " " * leftCount + word + " " * (width - word.size() - leftCount)
}

def right(width, word) {
return " " * (width - word.size()) + word
}

def alignColumns(align, text) {
def split := accum [] for line in text.split("\n") { _.with(line.split("$")) }
var widths := []
for line in split {
for i => word in line {
widths with= (i, widths.fetch(i, fn{0}).max(word.size()))
}
}
return accum "" for line in split {
_ + accum "" for i => word in line {
_ + align(widths[i] + 1, word)
} + "\n"
}
}</lang>

<lang e>? def 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."; null

? println(alignColumns(left, 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.

? println(alignColumns(center, 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.

? println(alignColumns(right, 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.</lang>


=={{header|Haskell}}==
=={{header|Haskell}}==