Is this an appropriate use of ContT?

Viewed 1697

I'm working on a project that requires me to write a small interpreter. The instructions have a simple tree structure and one of the commands has the effect of halting execution. So in the example below, "baz" is never printed.

import Control.Monad.Cont

data Instruction = Print String | Halt | Block [Instruction]
    deriving (Eq, Show)

instructions =
  [ Print "foo"
  , Block
    [ Print "bar"
    , Halt
    ]
  , Print "baz"
  ]

main :: IO ()
main = runContT (callCC $ interpret instructions)
                (const $ pure ())

interpret []     k = pure ()
interpret (a:as) k = case a of
    Print str -> liftIO (putStrLn str) >> interpret as k
    Block ins -> interpret ins k       >> interpret as k
    Halt      -> k ()

This is the first time I've seen a potential use for ContT in one of my projects. I was wondering if this is an appropriate use of it or if there is a simpler solution I might be overlooking.

1 Answers
Related