有条件的IO操作 [英] Conditional IO action

查看:112
本文介绍了有条件的IO操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,它应该能够直接从命令行读取输入或从文件读取输入,具体取决于传递的参数。例如。但是,我无法有条件地使IO事件。我首先想到的是:

  import System.Environment 
$ b $ main :: IO()
main = do
cla< - getArgs
let flags = parseFlags(filter isFlag cla)[]
let args = filter(not.isFlag)cla
input< ; - 如果(eleme标志)then(head args)else(readFile(head args))



<但是这不起作用,因为(head args)不是IO动作。我的下一个想法是:

  import System.Environment 
$ b $ main :: IO()
main = do
cla< - getArgs
let flags = parseFlags(filter isFlag cla)[]
let args = filter(not.isFlag)cla
file< ; - (readFile(head args))
let input = if(elemeflags)then(head args)else(file)

但是,如果输入不是文件的名称,这将会报错。有没有一个明智的方法来做到这一点?我正在处理这个问题吗?

c $ c>好像它在IO monad中一样。由于它只是一个原始值,因此在将其用作IO操作之前,需要将它放入monad中。

只需将(head args)更改为(return(head args)) code>。


I am writing a program that should be able to read input either from the command line directly or from a file depending on what args are passed. For example. However I am having trouble making the IO event conditional. My first thought was to do:

import System.Environment

main :: IO ()
main = do
 cla <- getArgs
 let flags = parseFlags (filter isFlag cla) []
 let args  = filter (not.isFlag) cla
 input <- if (elem "e" flags) then (head args) else (readFile (head args))

However this doesn't work because (head args) is not a IO action. My next thought was to do:

import System.Environment

main :: IO ()
main = do
 cla <- getArgs
 let flags = parseFlags (filter isFlag cla) []
 let args  = filter (not.isFlag) cla
 file <- (readFile (head args))
 let input = if (elem "e" flags) then (head args) else (file)

But this will error if the input is not the name of a file. Is there a sensible way to do this? Am I approaching the problem incorrectly?

解决方案

You were trying to treat (head args) as though it was in the IO monad. Since it's just a raw value, you need to place it into the monad before it can be used as an IO action.

Just change (head args) to (return (head args)).

这篇关于有条件的IO操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆