基于其他类似的问题,我发现我的问题与缩进有关,但我已经搞砸了很多,但仍然无法弄清楚。
addBook = do
putStrLn "Enter the title of the Book"
tit <- getLine
putStrLn "Enter the author of "++tit
aut <- getLine
putStrLn "Enter the year "++tit++" was published"
yr <- getLine
基于其他类似的问题,我发现我的问题与缩进有关,但我已经搞砸了很多,但仍然无法弄清楚。
addBook = do
putStrLn "Enter the title of the Book"
tit <- getLine
putStrLn "Enter the author of "++tit
aut <- getLine
putStrLn "Enter the year "++tit++" was published"
yr <- getLine
在您的情况下,这不是缩进;你真的已经用不是表达式的东西完成了你的功能。 yr <- getLine——在这之后,你预计会发生什么yr,或者aut就此而言?它们只是悬空,未使用。
显示它是如何翻译的可能更清楚:
addBook = putStrLn "Enter the title of the Book" >>
getLine >>= \tit ->
putStrLn "Enter the author of "++ tit >>
getLine >>= \aut ->
putStrLn "Enter the year "++tit++" was published" >>
getLine >>= \yr ->
那么,你想在最后一个箭头之后得到什么?
想想addBook. 那里……什么都没有IO a。a那是行不通的。你的 monad 必须有一些结果。
您可能想在最后添加类似这样的内容:
return (tit, aut, yr)
或者,如果您不想得到任何有用的结果,请返回一个空元组(一个单元):
return ()
如果你拿你的代码:
addBook = do
putStrLn "Enter the title of the Book"
tit <- getLine
putStrLn "Enter the author of "++tit
aut <- getLine
putStrLn "Enter the year "++tit++" was published"
yr <- getLine
并将其“翻译”为“正常”(非do)符号(给定p = putStrLn "..."):
addBook =
p >> getLine >>= (\tit ->
p >> getLine >>= (\aut ->
p >> getLine >>= (yr ->
你最终(yr ->没有意义。如果您没有其他有用的事情要做,则可以返回一个空元组:
return ()
在末尾:
addBook = do
putStrLn "Enter the title of the Book"
tit <- getLine
putStrLn "Enter the author of "++tit
aut <- getLine
putStrLn "Enter the year "++tit++" was published"
yr <- getLine
return ()
您可能应该问自己为什么需要获取aut以及yr尽管。
删除最后一行,因为它不是表达式,然后对传递给 putStrLn 的字符串使用括号。