TAGS :Viewed: 6 - Published at: a few seconds ago

[ Haskell call function onload ]

Good morning fellow programmers!

i'm working on a project using haskell, and i've wanted to know how to run a haskell function without having to type two lines on ghci, for example

ghci filename.hs function

This can only be done doing:

 ghci filename.hs

???? I'm looking for something like the main () in C,which runs automatically when you compile the program Is there something like that? I've been checking the -e option on ghci, but i cant seem to get it to work!

Thank you very much!


Answer 1

You're probably looking for ghc -e instead:

> echo 'foo x y z = x+y*z' > foo.hs  % let's make a foo.hs file
> ghc foo.hs -e 'foo 1 2 3'          % call the function in foo.hs
=> 7

Also, note that you can also use the :reload command in ghci. Load the file in ghci, edit, type :reload and test again. Also, if this seems too tedious, you can also define a ghci macro which allows you to reload and test your function at the same time:

> :def test \x -> return (":reload\n" ++ x)
> :test foo 1 2 3
=> Ok, modules loaded: Foo.

If you're looking to build real programs instead of quickly testing your functions, then you'd better read the other answers on writing main functions.

Answer 2

I assume function has the type IO (). Then you can just let main = function, and use for example runhaskell modulename from the command line. As in C, main is a special function.

To clarify a bit, just in case: If your function is a pure one, i.e. one whose type does not invovle IO, you can't really "run it". I guess it's a simplification to say this, but essentially what GHCi does is to call print function. If you want to mimic this, you can use something like main = print function and use runhaskell. This assumes function's type is an instance of Show.