问题
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.
回答1:
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 []
来源:https://stackoverflow.com/questions/37908718/keeping-track-of-history-in-ghci