[英]Haskell getArgs type is `Char` instead of `[Char`]
I am trying to get command line arguments to work with Haskell.我正在尝试获取命令行参数以使用 Haskell。 I currently have
我目前有
args ← getArgs
-- opens text file, uses handle for text
handle ← openFile args ReadMode
However, when I compile I am told that args is of type Char
, not [Char]
, therefore, I cannot open the file.但是,当我编译时,我被告知 args 是
Char
类型,而不是[Char]
,因此,我无法打开文件。 Is there another way to take in arguments in Haskell or am I taking mine in incorrectly?有没有另一种方法可以在 Haskell 中接受论点,还是我错误地接受了我的论点?
openFile :: FilePath -> IOMode -> IO Handle
takes a FilePath
and an IOMode
and gives an IO Handle
. openFile :: FilePath -> IOMode -> IO Handle
接受一个FilePath
和一个IOMode
并给出一个IO Handle
。
This means that这意味着
do
args <- getArgs
handle <- openFile args ReadMode
...
is claiming that args
has type FilePath
.声称
args
类型为FilePath
。 However, the type of getArgs :: IO [String]
means that args
is a [String]
, not a FilePath
.但是,
getArgs :: IO [String]
的类型意味着args
是[String]
,而不是FilePath
。 This means that you are calling openFile
with a list of strings rather than a file path.这意味着您正在使用字符串列表而不是文件路径调用
openFile
。
To fix this, first we must know that FilePath
is just a type synonym for String
, which means that we must take an element of args
rather than the whole list.要解决这个问题,首先我们必须知道
FilePath
只是String
的类型同义词,这意味着我们必须采用args
元素而不是整个列表。
Here is an example that does so using pattern matching:这是一个使用模式匹配的示例:
do
[arg] <- getArgs
handle <- openFile arg ReadMode
...
However, if the caller of your program provides the wrong number of arguments, this will cause an obscure runtime error (generated by fail
from the pattern matching failure).但是,如果你的程序的调用者提供了错误的参数数目,这将导致一个不起眼的运行时错误(所产生的
fail
从模式匹配失败)。 A more robust program might handle these cases with more descriptive failure messages:一个更健壮的程序可能会使用更具描述性的失败消息来处理这些情况:
do
args <- getArgs
case args of
[] -> error "must supply a file to open"
[arg] -> do handle <- openFile arg ReadMode
...
_ -> error "too many arguments"
As it turns out, it is a simple matter of parsing, the following code works事实证明,这是一个简单的解析问题,以下代码有效
args <- getArgs
let incomming = head args
handle ← openFile incomming ReadMode
you have to parse the argument.你必须解析这个论点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.