问题
I am trying to understand getArgs
in Haskell. Here is what I have:
import System.Environment
myFunFunction = do
args <- getArgs
return $ head args
What I am getting when I run the function is
*Main> myFunFunction
*** Exception: Prelude.head: empty list
Does this not work the same way as getLine
? Why does it not ask for a command line argument?
回答1:
The type of getArgs
is IO [String]
. When you bind it with <-
, as in the OP, the bound symbol (args
) gets the type [String]
, i.e. a list of strings.
The head
function returns the first element in a list; it has the type [a] -> a
. It's (in)famous for being unsafe, in the sense that if you apply it to an empty list, it'll crash:
Prelude System.Environment> head []
*** Exception: Prelude.head: empty list
That's what's happening here. getArgs
gives you the arguments you supplied at the command line when you ran the program. If you don't supply any arguments at the command line, then the returned list will be empty.
The getArgs
function isn't interactive. It'll just return the arguments supplied from the command line, if any were supplied.
来源:https://stackoverflow.com/questions/49055999/how-does-getargs-work