Ormolu saves the day

I had a surprising and amusing experience using Ormolu that I thought would be interesting for others to see. I was really puzzled why this code behaved incorrectly. One of the strange behaviours was that sometimes H wasn’t being printed.

"\ESC["
  ++ show (if wasWrapnext then oldym1 + 1 else oldym1)
  ++ ";"
  ++ if wasWrapnext then "1" else show (oldxm1 + 1)
  ++ "H"

After 30 minutes of trying to debug it I absent mindedly formatted with Ormolu, revealing the error. The H is part of the else branch!

"\ESC["
  ++ show (if wasWrapnext then oldym1 + 1 else oldym1)
  ++ ";"
  ++ if wasWrapnext
    then "1"
    else
      show (oldxm1 + 1)
        ++ "H"
18 Likes

@brandonchinn178 should add a “happy customers” section in fourmolu’s readme!

1 Like

Is there any extension for this case?

No extension needed:

"\ESC["
  ++ show (if wasWrapnext then oldym1 + 1 else oldym1)
  ++ ";"
  ++ id (if wasWrapnext then "1" else show (oldxm1 + 1))
  ++ "H"

You can also do this:

"\ESC["
  ++ show (if wasWrapnext then oldym1 + 1 else oldym1)
  ++ ";"
  ++ do if wasWrapnext then "1" else show (oldxm1 + 1)
  ++ "H"

Better would be to just mconcat though, imo:

mconcat
  [ "\ESC["
  , show (if wasWrapnext then oldym1 + 1 else oldym1)
  , ";"
  , if wasWrapnext then "1" else show (oldxm1 + 1)
  , "H"
  ]
5 Likes

By far the simplest way to correct the code is to use parentheses! It’s spotting the need to correct the code that was the difficult thing.

"\ESC["
  ++ show (if wasWrapnext then oldym1 + 1 else oldym1)
  ++ ";"
  ++ (if wasWrapnext then "1" else show (oldxm1 + 1))
  ++ "H"
7 Likes

You’re not the only one to have run into this issue! The precedence of if...then...else syntax is unclear at best and undocumented at worst. As a heavy autoformatter I’m rhapsodic that external formatting tools behave correctly here, because in my workflow, if something is improperly formatted, it’s likely improperly written!

1 Like

is that not a case to include if in the BlockArgument extension ?

No:

…that “trash fire” has more than enough to burn, thanks!