1 (* Copyright (C
) 1999-2006 Henry Cejtin
, Matthew Fluet
, Suresh
2 * Jagannathan
, and Stephen Weeks
.
4 * MLton is released under a BSD
-style license
.
5 * See the file MLton
-LICENSE for details
.
8 structure Justify
: JUSTIFY
=
24 val layout
= Layout
.str
o toString
26 fun spaces n
= S
.make (n
, C
.space
)
28 fun justify (s
, width
, just
) =
29 let val numchars
= S
.size s
30 val numspaces
= width
- numchars
33 Left
=> [s
, spaces numspaces
]
34 | Center
=> let val numLeft
= numspaces
div 2
35 val numRight
= numspaces
- numLeft
36 in [spaces numLeft
, s
, spaces numRight
]
38 | Right
=> [spaces numspaces
, s
])
41 fun table
{columnHeads
: string list option
,
43 rows
: string list list
} =
50 List.fold (headsAndRows
,
51 List.revMap (justs
, fn _
=> 0),
53 List.map2 (row
, ms
, fn (s
, m
) => Int.max (m
, String.size s
)))
55 List.map (rows
, fn row
=> List.map3 (row
, maxs
, justs
, justify
))
61 val heads
= List.map2 (heads
, maxs
, fn (s
, i
) =>
62 justify (s
, i
, Center
))
63 val dashes
= List.map (maxs
, fn i
=> String.make (i
, #
"-"))
65 heads
:: dashes
:: rows
72 Trace
.trace ("Justify.table",
73 fn {columnHeads
, justs
, rows
} =>
74 Layout
.record
[("columnHeads",
75 Option
.layout (List.layout
String.layout
)
77 ("justs", List.layout layout justs
),
79 List.layout (List.layout
String.layout
) rows
)],
80 List.layout (List.layout
String.layout
))
83 fun tableOfColumns (columns
: (t
* string list
) list
) =
85 val justs
= List.map (columns
, #
1)
86 val columns
= List.map (columns
, #
2)
87 fun loop (columns
: string list list
, ac
: string list list
) =
88 if List.isEmpty (hd columns
)
90 else loop (List.map (columns
, tl
), List.map (columns
, hd
) :: ac
)
91 val rows
= loop (columns
, [])
93 table
{columnHeads
= NONE
,
98 fun outputTable (t
, out
) =
100 val print
= Out
.outputc out
102 List.foreach (t
, fn ss
=>
107 ; List.foreach (ss
, fn s
=> (print
" "; print s
)))