【问题标题】:How to Pass a Function w/ an Argument to Another Function in Haskell?如何将带参数的函数传递给 Haskell 中的另一个函数?
【发布时间】:2017-10-04 19:00:22
【问题描述】:

我正在制作一个简单的 Haskell 待办事项列表,我想递归调用一个函数“提示”并根据用户输入显示不同的菜单选项。问题是,在初始调用时,prompt 应该期望接收一个函数作为不期望任何参数本身的参数之一。 “提示”的任何后续调用都可能需要调用一个函数,该函数确实期望将参数传递给正在传递给提示的函数。

这是我的代码:

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

我尝试这样做时遇到的错误是:

无法匹配预期类型“[Char] -> IO ()” 实际类型为“IO ()” • 函数“prompt”应用于三个参数, 但是它的类型‘[String] -> IO() -> IO()’只有两个

【问题讨论】:

    标签: haskell


    【解决方案1】:

    在这条线上

    | input == "+" = prompt todos subMenuOptions "add"
    

    首先,prompt 只接受 2 个参数,而我们传递了三个参数,就像错误所说的那样。对于prompt 的第二个参数,我们希望使用subMenuOptionsIO () 传递给它

    subMenuOptions :: [String] -> String -> IO ()
    

    这表示如果我们给它一个字符串列表和一个字符串,它将给我们我们正在寻找的IO ()。所以:

    | input == "+" = prompt todos (subMenuOptions todos "add")
    

    我们需要括号,因为

    prompt todos subMenuOptions todos "add"
    

    意味着我们将 4 个参数传递给 prompt

    【讨论】:

    • 谢谢!我向上帝发誓,我以前曾尝试过,但显然当时还有其他东西不起作用。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-01-06
    • 2010-10-22
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多