gpt4 book ai didi

haskell - 如何将带参数的函数传递给 Haskell 中的另一个函数?

转载 作者:行者123 更新时间:2023-12-01 11:18:56 24 4
gpt4 key购买 nike

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

我尝试执行此操作时遇到的错误是:

Couldn't match expected type ‘[Char] -> IO ()’ with actual type ‘IO ()’ • The function ‘prompt’ is applied to three arguments, but its type ‘[String] -> IO () -> IO ()’ has only two

最佳答案

在这条线上

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

首先,prompt 只需要 2 个参数,而我们传递了三个参数,就像错误所说的那样。对于 prompt 的第二个参数,我们希望使用 subMenuOptions

将其传递给 IO ()
subMenuOptions :: [String] -> String -> IO ()

它说如果我们给它一个字符串列表和一个字符串,它就会给我们我们要找的IO()。所以:

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

我们需要括号因为

prompt todos subMenuOptions todos "add"

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

关于haskell - 如何将带参数的函数传递给 Haskell 中的另一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46572291/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com