WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Haskell · Intermediate · question 29 of 100

What is the purpose of the main function in Haskell?

📕 Buy this interview preparation book: 100 Haskell questions & answers — PDF + EPUB for $5

The ‘main‘ function in Haskell serves as the entry point of a Haskell program. It is where the program starts executing when it is run. In other programming languages like C, Java, and Python, the main function serves a similar purpose.

In Haskell, the type signature of the main function is:

main :: IO ()

This means that the ‘main‘ function must return an IO action which, when executed, would produce a value of the unit type ‘()‘. The ‘IO‘ monad is used to encapsulate side effects, such as reading from and writing to the console, reading and writing files, and generating random numbers. Since Haskell is a purely functional language, program execution is modeled through a sequence of IO actions, which are executed by the runtime system when the program is run.

Here is an example of a simple Haskell program that uses a ‘main‘ function:

import System.Environment (getArgs)

-- A helper function that calculates the nth Fibonacci number
fibonacci :: Integer -> Integer
fibonacci n = fibs !! fromIntegral n
  where
    fibs = 0 : 1 : zipWith (+) fibs (tail fibs)

-- The main function of this program
main :: IO ()
main = do
  args <- getArgs
  let n = read (head args) :: Integer
  putStrLn ("The " ++ show n ++ "th Fibonacci number is " ++ show (fibonacci n))

In this program, the ‘main‘ function reads command-line arguments, converts the first argument to an integer ‘n‘, calculates the nth Fibonacci number using a helper function, and prints the result.

When compiled and executed, this program would behave as follows:

$ ghc -o fibonacci Fibonacci.hs
$ ./fibonacci 10
The 10th Fibonacci number is 55

In summary, the main function in Haskell serves as the entry point of a program, where the program starts executing when it is run. It has a type of ‘IO ()‘, which allows it to perform IO actions and return a value of the unit type ‘()‘.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Haskell interview — then scores it.
📞 Practice Haskell — free 15 min
📕 Buy this interview preparation book: 100 Haskell questions & answers — PDF + EPUB for $5

All 100 Haskell questions · All topics