我有一个包含列表的函数。我只想在用户输入后从主文件中将列表内容写入文件中。
putTodo :: (Int, String) -> IO ()
putTodo (n, todo) = putStrLn (show n ++ ": " ++ todo)
prompt :: [String] -> IO ()
prompt todos = do
putStrLn "The list contains:"
mapM_ putTodo (zip [0..] todos)
putStrLn " "
command <- getLine
getCommand command todos
我尝试过的事情:
main = do
outh <- openFile "agenda.txt" WriteMode;
hPutStrLn outh prompt[]
-- hPutStrLn outh (show prompt[])
-- hPrint (show prompt[])
hClose outh;
谢谢。
答案 0 :(得分:4)
您的代码包含几个错误/问题:
prompt[]
无效(在main
中)-应该是prompt
hPutStrLn
期望以String
作为第二个参数,但是您提供了IO()
getCommand
未定义您需要的是:
hPutStrLn
将此字符串打印到输出文件这是一个简单的版本,带有待办事项的硬编码列表(我的Haskell不太先进,因此可以用一种更为优雅的方式完成):
import System.IO
type Todo = (Int, String)
todoToString :: Todo -> String
todoToString (idx, name) = (show idx) ++ " : " ++ name
todosToString :: [Todo] -> String
todosToString todos = foldl (\acc t -> acc ++ "\n" ++ (todoToString t)) "" todos
allTodos :: [Todo]
allTodos = [(1, "Buy milk"), (2, "Program Haskell")]
main = do
outh <- openFile "agenda.txt" WriteMode;
hPutStrLn outh (todosToString allTodos);
hClose outh;