How does getArgs work?

我的未来我决定 提交于 2020-01-04 14:02:56

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!