Sunday 1 May 2016

Haskell: Writing standalone programs


Till now, I showed you how to load a module and call them in GHCi interpreter, but in real world, you need to write standalone programs. In this post, I am going to show you how to develop standalone programs.

How to develop a standalone program?
You need to define a module Main, with function main and of type IO ().

HelloWorld.hs
module Main where

    main = putStrLn "Hello"


To create an executable, ghc expects a module named Main that contains a function named main. Use the command ‘ghc --make -o hello HelloWorld.hs’ to generate executable.
$ ghc --make -o hello HelloWorld.hs
[1 of 1] Compiling Main             ( HelloWorld.hs, HelloWorld.o )
Linking hello ...
$ ./hello
Hello


Suppose if your Main module refers other modules, then the --make flag tells GHC to automatically detect dependencies in the files you are compiling.

Example
Data.hs
module Data where
    welcome = "Hello PTR!"


HelloWorld.hs
module Main where
    import Data
    
    main = putStrLn welcome

$ ghc --make -o hello HelloWorld.hs
[1 of 2] Compiling Data             ( Data.hs, Data.o )
[2 of 2] Compiling Main             ( HelloWorld.hs, HelloWorld.o )
Linking hello ...
$
$ ./hello
Hello PTR!


Specify source files location using –i option
HaskellProject/
   src/
      Main.hs
      Mathematics/
           Arithmetic.hs


Suppose, if you project structure looks like above.

Arithmetic.hs
-- Arithmetic module implements simple Arithmetic functions
 module Mathematics.Arithmetic where
    addition :: Integer -> Integer -> Integer
    addition x y = (x+y)

    sub :: Integer -> Integer -> Integer
    sub x y = (x-y)

    mul :: Integer -> Integer -> Integer
    mul x y = (x*y)

    divide :: Integer -> Integer -> Double
    divide x y = (fromIntegral x / fromIntegral y)


Main.hs
module Main where
    import Mathematics.Arithmetic

    main = putStrLn (show(addition 10 20) ++ "," ++ show(sub 10 20))


‘ghc --make -i/Users/harikrishna_gurram/study1/Haskell/programs -o hello Main.hs’ compiles Main.hs and generate the executabe hello.
$ ghc --make -i/Users/harikrishna_gurram/study1/Haskell/programs -o hello Main.hs
[1 of 2] Compiling Mathematics.Arithmetic ( Mathematics/Arithmetic.hs, Mathematics/Arithmetic.o )
Linking hello ...
$
$ ./hello
30,-10


Previous                                                 Next                                                 Home

No comments:

Post a Comment