Skip to content

Instantly share code, notes, and snippets.

@tomykaira
Created July 26, 2011 12:29
Show Gist options
  • Save tomykaira/1106638 to your computer and use it in GitHub Desktop.
Save tomykaira/1106638 to your computer and use it in GitHub Desktop.
module Main where
-- モナド: 型構成子、 return、 バインド
data Position t = Position t deriving (Show) -- 型構成子、 自家製モナド
stagger (Position d) = Position (d + 2)
crawl (Position d) = Position (d + 1)
rtn x = x -- return のかわり
x >>== f = f x -- bind(>>=) のかわり
treasureMap pos = pos >>==
stagger >>== -- stagger pos >>==
stagger >>== -- stagger stagger pos >>==
crawl >>== -- crawl stagger stagger pos >>==
rtn -- crawl stagger stagger pos
@md2perpe
Copy link

You can use the state monad:

module Main where

    import Control.Monad.State

    stagger :: State Integer ()
    stagger = do
        d <- get
        put (d+2)

    crawl :: State Integer ()
    crawl = do
        d <- get
        put (d+1)

    treasureMap :: State Integer () 
    treasureMap = do
        stagger
        stagger
        crawl

    follow :: Integer -> Integer
    follow d = execState treasureMap d

@tomykaira
Copy link
Author

Thanks, looks great!
I am just a beginner. Using monad is hard :<

My original code is in "Sevel Languages in Seven Weeks".
The author's intention is maybe learning HOW a monad works.

@md2perpe
Copy link

I think that monads can be easy and difficult at the same time. They can make the code very readable and easy to understand, but it can be difficult to create them.

In the code above I'm using "syntactic sugar" which makes the code more similar to imperative program code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment