real language

Bookmarking Digg Diigo DZone Earthlink Google
Windows Live LookLater Ma.gnolia Reddit Rojo StumbleUpon Technorati

Language Haskell

(With monads and monad transformer)

Author:Adrien Piérard
Score: (3.01 in 147 votes)
Haskell isn't fun unless you use monads.
Monads aren't fun unless you use monad transformers :)


import Control.Monad.State

-- new data type
data Beer = B Int

-- factorize code a little bit
tk = "Take one down and pass it around, "
wall = " of beer on the wall.\n"
end 1 =  tk++"1 bottle"++ wall
end n =  tk++show n++" bottles"++wall

-- define the way our brand new data type shows up 
instance Show Beer where
  show (B 0) = "No more bottle of beer on the wall, no more bottle of beer.\n"
         ++ "Go to the store and buy some more, 99 bottles of beer on the wall."
  show (B 1) = "1 bottle of beer on the wall, 1 bottle of beer.\n"++end 0
  show (B n)   = show n++ " bottles of beer on the wall, " ++ show n ++
                 " bottles of beer.\n"++end (n-1)

-- This is not even a function, though it's recursive
-- Makes use of the IO monad over a State Int () monad
verse :: StateT Int IO ()
verse = do
  cpt <- get
  liftIO $ print (B cpt)
  put (cpt-1)
  if (cpt >=1) then verse else return ()

-- I say "now" !
main = runStateT verse 99

Download Source | Write Comment

Alternative Versions

Using guardsSimon Johansson10/25/073
Using list comprehensionBen Firner11/21/080


>>  Daniel said on 03/23/07 13:38:36

Daniel This version doesn't work with hugs:

ERROR "/opt/local/lib/hugs/packages/mtl/Control/Monad/Reader.hs":47 - Haskell 98 does not support dependent parameters

unless you start up Hugs with Haskell 98 extensions:

> hugs -98

(then load your file with this in)

>>  Jack said on 09/09/08 22:52:30

Jack or you could change your option in Hugs to allow extensions...

Download Source | Write Comment

Add Comment

Please provide a value for the fields Name, Comment and Security Code.
This is a gravatar-friendly website.
E-mail addresses will never be shown.
Enter your e-mail address to use your gravatar.

Please don't post large portions of code here! Use the form to submit new examples or updates instead!




Security Code: