Look mom.. My first Haskell code

These days I am trying my hardest to learn Haskell.
Found these 2 great online resources Real World Haskell and Learn You a Haskell.

An attempt to solve a rather simple problem from codechef took me close to 2 days.
Not due to the lack of looping constructs..
Nor because I cannot think recursively.
But primarily due to the fact that Haskell doesn’t make it easy to mix pure and impure code.
It took me quite a while to understand that a little monadic constructs such as mapM, forM exists. And the let bindings for sprinkling pure code in between impure code.

But it was worth it though.
Here I present my first ever Haskell program in all its elegance. :))

import Control.Monad

factorial :: Integer -> Integer
factorial x = product [1..x]

main = do
n <- readLn

— Read n numbers and store them in a list
inputList <- forM [1..n] (\a -> readLn)

let outputList = map factorial inputList
mapM_ print outputList

O’course, forM could well be substituted for mapM but with the parameters flipped.
But I find the forM version more readable.

import Control.Monad

factorial :: Integer -> Integer
factorial x = product [1..x]

main = do
n <- readLn

— Read n numbers and store them in a list
inputList <- mapM (\a -> readLn) [1..n]

let outputList = map factorial inputList
mapM_ print outputList

Niranjan Nagaraju

I am Vini – Vini The Pooh aka Niranjan. I am a little “sheep in the big city”. A self-proclaimed atheist, freelance writer and cartoonist; The latter two are an avocation as yet, but I believe they really are my medium. Oh, and I code for a living. :)

Leave a Reply

Your email address will not be published. Required fields are marked *