Skip to content

Instantly share code, notes, and snippets.

@jutememo
Created November 10, 2009 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jutememo/230501 to your computer and use it in GitHub Desktop.
Save jutememo/230501 to your computer and use it in GitHub Desktop.
module Counter where
-- カウンタを表わす型
data Counter a = Counter { val -- 値
, step :: a -- 増分
} deriving Show
-- カウンタの値を増加させる
next :: Num a => Counter a -> (a, Counter a)
next (Counter v s) = let v' = v + s
in (v', Counter v' s)
-- カウンタ操作型を定義
type CounterOp a b = Counter a -> (b, Counter a)
-- カウンタ操作型をつなげる関数
comb :: CounterOp a b -> (b -> CounterOp a c ) -> CounterOp a c
comb m n = \counter0 -> let (val1, counter1) = m counter0
(val2, counter2) = n val1 counter1
in (val2, counter2)
comb_ :: CounterOp a b -> CounterOp a c -> CounterOp a c
comb_ m n = m `comb` \_ -> n
ret :: b -> CounterOp a b
ret x = \counter -> (x, counter)
-- next を 3 回つなげた関数
next3 = next `comb_` next `comb_` next
-- next を 3 回つなげて、カウンタの値を足し合わせる関数
next3' = next `comb` \x1 ->
next `comb` \x2 ->
next `comb` \x3 ->
ret $ x1+x2+x3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment