I'm somewhat new to Haskell. I've worked through one ore two tutorials, but I don't have much experience.
Every function in Haskell is pure, this is, why we can't have any I/O without the IO-monad. What I don't understand is, why do the program parameters have to be an IO action as well? The parameters are passed to the program like to a function. Why can't the parameters be accessed like in a function?
To make things clear, I don't understand, why the main function has to look like this
main :: IO()
main = do
args <- getArgs
print args
Instead of this
main :: [String] -> IO()
main args = do
print args
I can't see any reason for it, and I haven't found an answer googling around.
It's a language design choice. Neither approach is strictly better than the other one.
Haskell could have been designed to have a main
of either kind.
When one does need the program arguments, it would be more convenient to have them passed as function arguments to main
.
When one does not need the program arguments, having them passed to main
is slightly cumbersome, since we need to write a longer type, and an additional _
to discard the [String]
argument.
Further, getArgs
lets one access the program arguments anywhere in the program (inside IO
), while having them passed to main
, only, can be less convenient since one would then be forced to pass them around in the program, which can be inconvenient.
(Short digression) For what it's worth, I had a similar reaction to yours a long time ago when I discovered that in Java we have void main()
instead of int main()
as in C. Then I realized that in most programs I always wrote return 0;
at the end, so it makes little sense to always require that. In Java that's the implicit default, and when we really need to return something else, we use System.exit()
. Even if that is the way it's done in a previous language (C, in this case), new languages can choose a new way to make available the same functionality.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With