Voting

Category

real language

Bookmarking

Del.icio.us Digg Diigo DZone Earthlink Google Kick.ie
Windows Live LookLater Ma.gnolia Reddit Rojo StumbleUpon Technorati

Language Haskell

(With monads and monad transformer)

Date:12/25/06
Author:Adrien Piérard
URL:n/a
Comments:2
Info:http://haskell.org
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

VersionAuthorDateCommentsRate
1Iavor03/03/065
Using guardsSimon Johansson10/25/073
Using list comprehensionBen Firner11/21/080

Comments

>>  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!

Name:

eMail:

URL:

Security Code:
  
Comment: