简体   繁体   English

Haskell getArgs 类型是 `Char` 而不是 `[Char`]

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM