Haskell:没有 "do" 符号的 getLine 中的字数

Haskell: words count from a getLine without the "do" notation

如何在不使用 "do" 符号的情况下编写以下函数?

wordsCount =  do 
    putStr "Write a line and press [enter]:\n"
    s <- getLine
    putStr $ show $ length . words $ s
    putChar '\n'

而不是使用do, you can use >> and >>=

wordsCount = putStr "Write a line and press [enter]:\n" >> getLine >>= putStr . show . length . words >> putChar '\n'

或使其更易于阅读:

wordsCount = putStr "Write a line and press [enter]:\n" >>
    getLine >>=
    putStr . show . length . words >>
    putChar '\n'

更直接的翻译是:

wordsCount = putStr "Write a line and press [enter]:\n" >>
    getLine >>=
    \s -> (putStr $ show $ length $ words s) >>
    putChar '\n'

基本上,编译器将这样的 do-notation 块转换为它的 monadic 等价物(仅使用 >>>>=)。 do 只是语法糖,这样就不必每次都写 >>= and/or 管理变量。

补充说明:

  • 正如@ChadGilbert 在 中所说,括号应该包含在函数周围,不包括 \s ->,以便稍后可以使用 s在程序中,例如:

    -- This is not an equivalent program
    wordsCount = putStr "Write a line and press [enter]:\n" >>
        getLine >>=
        \s -> (putStr $ show $ length $ words s) >>
        putChar '\n' >>
        putStrLn s -- repeat s
    
  • 您可以使用 putStrLn 而不是 putStrputChar。例如:

    wordsCount = putStr "Write a line and press [enter]:\n" >>
        getLine >>=
        putStrLn . show . length . words