6

私が見つけた他の同様の質問に基づいて、私の問題はインデントに関係していると思いますが、私はそれをたくさんいじりましたが、まだ理解できません。

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
4

4 に答える 4

19

あなたの場合、それはインデントではありません。式ではない何かで関数を本当に終了しました。 —この後、またはyr <- getLineさらに言えば、に何が起こると予想していましたか? ぶら下がっているだけで、使用されていません。yraut

これがどのように変換されるかを示すと、より明確になる可能性があります。

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 ->

では、最後の矢印に続いて何をしたかったのでしょうか?

于 2012-04-07T21:12:29.847 に答える
8

の型を考えてみてくださいaddBook。それはIO aどこにaある...何もない。それはうまくいきません。モナドには何らかの結果が必要です。

最後に次のようなものを追加することをお勧めします。

return (tit, aut, yr)

または、有用な結果が必要ない場合は、空のタプル (ユニット) を返します。

return ()
于 2012-04-07T21:08:55.700 に答える
2

コードを取得する場合:

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ます。

于 2014-06-11T17:17:13.180 に答える