Keeping track of history in ghci

半腔热情 提交于 2020-01-04 07:11:29

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!