我正在制作一个简单的Haskell待办事项列表,我想以递归方式调用函数"提示",并根据用户输入显示不同的菜单选项.问题是,在初始调用时,提示应该期望接收一个函数作为不期望任何参数本身的参数之一.任何后续的"提示"调用可能需要调用一个函数,该函数期望将一个参数传递给正在传递给提示的函数.
这是我的代码:
mainMenuOptions :: IO ()
mainMenuOptions = do
putStrLn ""
putStrLn "What would you like to do?"
putStrLn ""
putStrLn "OPTIONS"
putStrLn ""
putStrLn "'+' : add items | '-' : remove items"
subMenuOptions :: [String] -> String -> IO ()
subMenuOptions todos operation = do
putStrLn ""
if operation == "add"
then do putStrLn ("Type in the TASK you'd like to " ++ operation ++ ", then hit ENTER")
addListItemOptions todos
else do
putStrLn ("Type in the NUMBER of the task you'd like to " ++ operation ++ ", then hit ENTER")
putStrLn "('r' : return to the main menu)"
prompt :: [String] -> IO () -> IO ()
prompt todos showOptions = do
showTasks todos
showOptions
input <- getLine
interpret input todos
interpret :: String -> [String] -> IO ()
interpret input todos
| input == "r" = prompt todos mainMenuOptions
| input == "+" = prompt todos subMenuOptions "add"
| input == "-" = prompt todos subMenuOptions "remove"
| otherwise = do
putStrLn ""
putStrLn "SORRY, did not get that! Please enter a valid option."
prompt todos mainMenuOptions
main :: IO ()
main = do
putStrLn "Haskell ToDo List"
prompt [] mainMenuOptions
Run Code Online (Sandbox Code Playgroud)
我尝试这样做时得到的错误是:
无法将预期类型'[Char] - > IO()'与实际类型'IO()'匹配•函数'prompt'应用于三个参数,但其类型为'[String] - > IO() - > IO()'只有两个
在这条线上
| input == "+" = prompt todos subMenuOptions "add"
Run Code Online (Sandbox Code Playgroud)
首先,prompt只需要2个参数,我们将它传递给3个,就像错误所说的那样.对于第二个参数prompt,我们希望有一个通过它IO ()使用subMenuOptions
subMenuOptions :: [String] -> String -> IO ()
Run Code Online (Sandbox Code Playgroud)
这说明如果我们给它一个字符串和字符串列表,它将给我们IO ()正在寻找的东西.所以:
| input == "+" = prompt todos (subMenuOptions todos "add")
Run Code Online (Sandbox Code Playgroud)
我们需要括号因为
prompt todos subMenuOptions todos "add"
Run Code Online (Sandbox Code Playgroud)
意味着我们要传递4个参数prompt.