如何在不使用“do”符号的情况下编写以下函数?
wordsCount = do
putStr "Write a line and press [enter]:\n"
s <- getLine
putStr $ show $ length . words $ s
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 >>=
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
表示法 block 转换为其等价的单子(monad)(仅使用 >>
和 >>=
)。 do
只是语法糖,因此不必每次都编写 >>=
和/或管理变量。
附加说明:
正如 @ChadGilbert 在 his comment 中所说,括号应括在函数周围,不包括
\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
而不是使用putStr
和putChar
。例如:wordsCount = putStr "Write a line and press [enter]:\n" >> getLine >>= putStrLn . show . length . words
关于Haskell:从 getLine 中计算字数,不带 "do"符号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37662754/