在 Haskell 中条件处理 IO 的惯用方法
我正在 Haskell 中编写一个小 shell 脚本,它可以接受可选参数。但是,如果参数不存在,我想从 stdin 获取一行来请求值。
在 Haskell 中执行此操作的惯用方法是什么?
#!/usr/bin/env runhaskell
import Control.Applicative ((<$>))
import Data.Char (toLower)
import IO (hFlush, stdout)
import System.Environment (getArgs)
main :: IO ()
main = do args <- getArgs
-- here should be some sort of branching logic that reads
-- the prompt unless `length args == 1`
name <- lowerCase <$> readPrompt "Gimme arg: "
putStrLn name
lowerCase = map toLower
flushString :: String -> IO ()
flushString s = putStr s >> hFlush stdout
readPrompt :: String -> IO String
readPrompt prompt = flushString prompt >> getLine
哦,如果有办法使用 Control.Applicative
或 Control.Arrow
中的某些内容来实现这一点,我想知道。我对这两个模块非常感兴趣。
谢谢!
I'm writing a little shell script in Haskell which can take an optional argument. However, if the argument is not present, I'd like to get a line from stdin in which to ask for a value.
What would be the idiomatic way to do this in Haskell?
#!/usr/bin/env runhaskell
import Control.Applicative ((<gt;))
import Data.Char (toLower)
import IO (hFlush, stdout)
import System.Environment (getArgs)
main :: IO ()
main = do args <- getArgs
-- here should be some sort of branching logic that reads
-- the prompt unless `length args == 1`
name <- lowerCase <gt; readPrompt "Gimme arg: "
putStrLn name
lowerCase = map toLower
flushString :: String -> IO ()
flushString s = putStr s >> hFlush stdout
readPrompt :: String -> IO String
readPrompt prompt = flushString prompt >> getLine
Oh, and if there's a way to do it with something from Control.Applicative
or Control.Arrow
I'd like to know. I've become quite keen on these two modules.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不适合您的特定用例,但问题标题让我立即想到
Control.Monad
中的when
。直接来自文档:示例:
您还可以以类似的方式使用
when
的表兄弟unless
。This doesn't fit your specific use case, but the question title made me think immediately of
when
fromControl.Monad
. Straight from the docs:Example:
You can also use
when
's cousinunless
in similar fashion.