Debian Codegraph @

tests/monad/fibonacci/Main.agda

raw
1 {-# OPTIONS --guardedness --rewriting #-}
2
3 module Main where
4
5 open import Data.Bool.Base using (Bool; true; false)
6 open import Data.Nat.Base using (ℕ; zero; suc; _+_)
7 open import Data.Nat.Show using (show)
8 open import Data.Product.Base using (_,_)
9 open import Data.String.Base using (String; _++_)
10
11 open import Data.Default
12 open import Debug.Trace using (trace)
13
14 open import IO.Base using (Main; run)
15 open import IO.Finite using (putStrLn)
16 open import Function.Base using (_$_)
17
18 open import Effect.Monad
19 open import Effect.Monad.State
20 open import Effect.Monad.State.Instances
21 open import Effect.Monad.Identity.Instances
22 open import IO.Instances
23
24 open RawMonad {{...}}
25 open RawMonadState {{...}}
26
27 record Fib : Set where
28 field tracing : Bool
29 index : ℕ
30 current : ℕ
31 next : ℕ
32 open Fib
33
34 initFib : Bool → Fib
35 initFib b = record
36 { tracing = b
37 ; index = 0
38 ; current = 0
39 ; next = 1
40 }
41
42 displayFib : ℕ → ℕ → String
43 displayFib idx fibn = "fib " ++ show idx ++ " = " ++ show fibn
44
45 fibM : ℕ → State Fib ℕ
46 fibM 0 = gets current
47 fibM (suc n) = do
48 b ← gets tracing
49 when b $ do
50 idx ← gets index
51 fibn ← gets current
52 trace (displayFib idx fibn) (pure _)
53 modify (λ r → record r { index = suc (index r) ; current = next r ; next = next r + current r })
54 fibM n
55
56 fib : ℕ → Bool → ℕ
57 fib n b = evalState (fibM n) (initFib b)
58
59 fibStr : ℕ → {{WithDefault false}} → String
60 fibStr n {{b}} = displayFib n (fib n (value b))
61
62 main : Main
63 main = run $ do
64 putStrLn $ fibStr 0
65 putStrLn $ fibStr 1
66 putStrLn $ fibStr 2
67 putStrLn $ fibStr 3
68 putStrLn $ fibStr 5
69 putStrLn $ fibStr 6
70 putStrLn $ fibStr 7
71 putStrLn $ fibStr 8
72 putStrLn $ fibStr 9
73 putStrLn $ fibStr 10