Language Haskell
(With monads and monad transformer)
| Date: | 12/25/06 |
| Author: | Adrien Piérard |
| URL: | n/a |
| Comments: | 1 |
| Info: | http://haskell.org |
| Score: |
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
| Version | Author | Date | Comments | Rate |
|---|---|---|---|---|
| Using guards | Simon Johansson | 10/25/07 | 1 | |
| 2 | Iavor | 03/03/06 | 3 |
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!
Comments
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)