Haskell中的简单文本菜单

gru*_*ber 6 haskell menu

我想知道创建具有下述功能的简单菜单(伪代码)的最佳解决方案是什么,就像我以前一样:

while (true) {
    x = readLine();
    case (x):
         x == "1" then do sth1 function
         x == "2" then do sth2 function
}
Run Code Online (Sandbox Code Playgroud)

或者也许关于如何使菜单不在上述模式中的任何其他想法?

Don*_*art 10

对于构建命令行系统的高级方法,有一些很酷的包:

  1. ui-command:友好命令行程序的框架
  2. haskeline:用户输入的命令行界面,用Haskell编写.
  3. HCL:用于构建命令行界面的高级库.

我特别喜欢ui-command,因为它是命令行工具的整个框架:它将分派给您为每个命令提供的处理程序函数,并为用户提供特定于命令的帮助.

目标是一种抛光的感觉,而不是一种hackish的感觉.


Luk*_*keN 6

就像是

menu :: IO ()
menu = do
      putStrLn . unlines $ map concatNums choices
      choice <- getLine
      case validate choice of
         Just n  -> execute . read $ choice
         Nothing -> putStrLn "Please try again"

      menu
   where concatNums (i, (s, _)) = show i ++ ".) " ++ s

validate :: String -> Maybe Int
validate s = isValid (reads s)
   where isValid []            = Nothing
         isValid ((n, _):_) 
               | outOfBounds n = Nothing
               | otherwise     = Just n
         outOfBounds n = (n < 1) || (n > length choices)

choices :: [(Int, (String, IO ()))]
choices = zip [1.. ] [
   ("DoSomething", foo)
 , ("Quit", bar)
 ]

execute :: Int -> IO ()
execute n = doExec $ filter (\(i, _) -> i == n) choices
   where doExec ((_, (_,f)):_) = f

foo = undefined
bar = undefined
Run Code Online (Sandbox Code Playgroud)

你可能可以在"选择"中拆分枚举,所以你只有里面的描述和功能,一点点分离,但这是有效的.评估"菜单"功能将让您选择做什么!