Haskell中的简单文本菜单 [英] Simple text menu in Haskell
本文介绍了Haskell中的简单文本菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道什么是使用下面描述的功能创建简单菜单的最佳解决方案(伪代码),就像我习惯的那样:
while(true){
x = readLine();
case(x):
x ==1然后做sth1函数
x ==2然后做sth2函数
}
或者也许有关于如何制作不在上述模式中的菜单的任何其他想法?
menu :: IO()
menu =做
putStrLn。 unlines $ map concatNums options
choice< - getLine
case valid validate choice of
Just n - >执行 。阅读$ choice
Nothing - > putStrLn请再试一次
menu
concatNums(i,(s,_))= show i ++)++ s
validate :: String - >也许Int
validate s = isValid(读取s)
其中isValid [] = Nothing
isValid((n,_):_)
| outOfBounds n = Nothing
|否则=只是n
outOfBounds n =(n <1)|| (n>长度选择)
choices :: [(Int,(String,IO()))]
choices = zip [1 ..] [
( DoSomething,foo)
,(Quit,bar)
]
execute :: Int - > IO()
执行n = doExec $ filter(\(i,_) - > i == n)options
其中doExec((_,(_,f)):_)= f
foo = undefined
bar =未定义
您可以可能会将枚举拆分为选项,因此只有它的描述和函数,有点分离,但这是有效的。评估菜单功能可以让你选择做什么!
I would like to know what is the best solution to create simple menu with functionality described below (pseudo code) just like I'm used to:
while (true) { x = readLine(); case (x): x == "1" then do sth1 function x == "2" then do sth2 function }
Or maybe any other ideas on how to make a menu not in the pattern described above?
解决方案Something like
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
You could probably split the enumerating in "choices" so you only have the descriptions and functions inside it, a little bit of separation, but this works. Evaluating the "menu" function will let you choose what to do!
这篇关于Haskell中的简单文本菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文