Skip to content

Commit 0fb4f15

Browse files
committed
Create render_table.ml
1 parent d38c90d commit 0fb4f15

1 file changed

Lines changed: 45 additions & 0 deletions

File tree

utils/render_table.ml

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
open Base;;
2+
open Stdio;;
3+
4+
let max_widths header rows =
5+
let lengths l = List.map ~f:String.length l in
6+
List.fold rows
7+
~init:(lengths header)
8+
~f:(fun acc row ->
9+
List.map2_exn ~f:Int.max acc (lengths row))
10+
;;
11+
12+
let render_separator widths =
13+
let pieces = List.map widths
14+
~f:(fun w -> String.make (w + 2) '-')
15+
in
16+
"|" ^ String.concat ~sep:"+" pieces ^ "|"
17+
;;
18+
19+
let pad s length =
20+
" " ^ s ^ String.make (length - String.length s + 1) ' '
21+
;;
22+
23+
let render_row row widths =
24+
let padded = List.map2_exn row widths ~f:pad in
25+
"|" ^ String.concat ~sep:"|" padded ^ "|"
26+
;;
27+
28+
let render_table header rows =
29+
let widths = max_widths header rows in
30+
String.concat ~sep:"\n"
31+
(render_row header widths
32+
:: render_separator widths
33+
:: List.map rows ~f:(fun row -> render_row row widths)
34+
)
35+
;;
36+
37+
Stdio.print_endline
38+
(render_table
39+
["language";"architect";"first release"]
40+
[ ["Lisp" ;"John McCarthy" ;"1958"] ;
41+
["C" ;"Dennis Ritchie";"1969"] ;
42+
["ML" ;"Robin Milner" ;"1973"] ;
43+
["OCaml";"Xavier Leroy" ;"1996"] ;
44+
])
45+
;;

0 commit comments

Comments
 (0)