dimid
dimid

Reputation: 7659

Keeping track of history in ghci

How does history management work in GHCI or other Haskell-based REPLs? Since Haskell is a pure language, I guess it's implemented using a monad, perhaps the state monad.

Kindly note I'm a beginner in Haskell, so please provide a detailed explanation rather than just linking to the source.

Upvotes: 2

Views: 411

Answers (1)

ErikR
ErikR

Reputation: 52067

This is a simplified example of how a program might keep a history of commands entered by the user. It basically has the same structure as the number guessing game, so once you understand that you should have no trouble understanding this:

import Control.Monad.State
import Control.Monad

shell :: StateT [String] IO ()
shell = forever $ do
  lift $ putStr "$ "
  cmd <- lift getLine
  if cmd == "history"
    then do hist <- get
            lift $ forM_ hist $ putStrLn
    else modify (++ [cmd])

main = do putStrLn "Welcome to the history shell."
          putStrLn "Type 'history' to see your command history."
          execStateT shell []

Upvotes: 2

Related Questions