Search code examples
ocamlocamllex

Printing an RLE list in OCaml


If I call my runlength encode program with encode[1;1;2], I get

int encode list = [Multiple (1, 2); Singles 1]

How would I get a bracket () for the Singles as well so it would be like [Multiple (1, 2); Singles (1)]?


Solution

  • That's just the way the OCaml toplevel prints values. If a data constructor has only one argument, it gets written without parentheses.

    If you want the output to look different, you have to write your own code to do the printing.

    Here's a session that shows how to do this using #install_printer:

    $ ocaml
            OCaml version 4.02.1
    
    # type r = Singles of int | Multiple of int * int;;
    type r = Singles of int | Multiple of int * int
    # let printr f = function
      | Singles x -> Format.fprintf f "Singles (%d)" x
      | Multiple (x, y) -> Format.fprintf f "Multiple (%d, %d)" x y
      ;;
    val printr : Format.formatter -> r -> unit = <fun>
    # #install_printer printr;;
    # Singles (3);;
    - : r = Singles (3)
    # Multiple (3, 5);;
    - : r = Multiple (3, 5)
    # [ Singles(1); Multiple(3, 5)];;
    - : r list = [Singles (1); Multiple (3, 5)]