Infix to postfix notation in Haskell (Shunting-yard algorithm)
main :: IO ()
main = do
  line &lt;- getLine
  putStrLn $ case traverse str2tok $ splitTok line of
    Left s -&gt; s
    Right ts -&gt; unwords $ map tok2str $ shuntYard ts

-- shuntYard (Token Buffer) = new Token Queue
shuntYard :: [Token] -&gt; [Token]
shuntYard ts = concat queue ++ stack where
  (queue, stack) = (`runState` []) $ for ts $ state . \case
    TNum t -&gt; ([TNum t],)
    TOp LBrace -&gt; ([],) . (LBrace :)
    TOp RBrace -&gt; (map TOp *** drop 1) . break (==LBrace)
    TOp t -&gt; (map TOp *** (t:)) . span (\op -&gt; precedence op &gt; precedence t &amp;&amp; op /= LBrace)


Or perhaps:

(queue, stack) = (`runState` []) $ for ts $ \case
  TNum t -&gt; return [TNum t]
  TOp LBrace -&gt; [] &lt;$ modify (LBrace:)
  TOp RBrace -&gt; do
    sstart &lt;- state $ break (==LBrace)
    modify (drop 1)
    return $ map TOp sstart
  TOp t -&gt; do
    ssops &lt;- state $ span $ \op -&gt; precedence op &gt; precedence t &amp;&amp; op /= LBrace
    modify (t:)
    return $ map TOp ssops