Richard Feldman's Console-Print Library

I’d like to put in a few words for Richard Feldman’s console-print library, which gives a convenient way to “print formatted text to the console using ANSI escape sequences.” This can be quite helpful in debugging or otherwise peering into the operation of your code.

As a silly example, consider the Collatz function. If n == 1, then collatz n == 1. If n is even, then collatz n = n // 2, otherwise collatz n = 3n + 1. Then in elm repl we have this:

Nice colors! No big deal here, but this comes in quite handy when the output is complicated and you need to be able to scan through it to find what you want.

Below is the code. The important part is Console.magenta, which prints its argument to the terminal in magenta. You could also use, say Console.bgCyan >> Console.white in place of this to have white text on a cyan background.

collatz n =
    let
        _ =  Debug.log (Console.magenta "collatz") n
    in
    if n == 1 then
        1
    else if modBy 2 n == 0 then
        collatz (n // 2)
    else
        collatz (3 * n + 1)

Below is a more substantial example from a parser project I was working on. I needed a way to track the state of the parser as it was chugging along. Different background colors were used to highlight different fields in the state. The gain in readability was a life-saver for me.

With Albert Dahlin’s elm-posix, there are likely many more uses of the console-print library.

6 Likes

Cool example for Debug.log! I hadn’t thought of that.

elm-review uses the same idea for its testing module. For instance, when your rule suggests a fix, the testing module checks whether the source code after the fix matches what was expected. If it doesn’t, it lets you know by showing you the actual and expected source code.

But sometimes, this can be hard to read when the difference is only whitespace, which is why when that happens a special message shows up where the whitespace is highlighted, and it looks like this:

The red at the top is the test title (colored by elm-test), then comes the error type (Fixed code mismatch) colored by the test module.

I have been made aware of that these colors don’t disappear when you run elm-test with --no-color, which is not ideal. I further described this approach in Great compiler messages? Great test failure messages!

1 Like

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.