-
Notifications
You must be signed in to change notification settings - Fork 75
/
Copy path02-Debug-Trace.purs
71 lines (51 loc) · 1.95 KB
/
02-Debug-Trace.purs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
-- When you compile this file, it will output compiler warnings.
-- If you wish to remove that noise, comment out everything below
-- the "module" declaration.
module Debugging.DebugTrace where
-- Comment out everything below this line to prevent compiler warning.
import Prelude
import Effect (Effect)
import Effect.Console (log)
import Debug.Trace (spy, trace, traceM)
-- Given a simple Box Monad
data Box a = Box a
-- all type class instances are at the end of the file
boxed4 :: Box Int
boxed4 = Box 4
runBox :: Box ~> Effect
runBox (Box a) = pure a
printAndReturnTheValue :: Int -> Int
printAndReturnTheValue x = spy "'x' is" x
printMessageThenRunComputation :: String -> (Unit -> Int) -> Int
printMessageThenRunComputation msg x = trace msg x
-- When running this, you'll notice that the debug messages
-- are outputted in a font color different than the normal output.
main :: Effect Unit
main = do
-- spy
log $ show $ printAndReturnTheValue 5
-- trace
log $ show $ printMessageThenRunComputation "before computation" (\_ -> 10)
log "Right now we are inside of the Effect monad context, \
\which means we CAN use the `log` function here."
value <- runBox do
four <- boxed4
-- now we are inside of the Box monad context,
-- which means we CANNOT use `log` here since
-- it returns `Effect Unit`, not `Box Unit`
-- Instead, we'll use traceM
-- Note: Using "traceM" without there being a monad instance
-- for Box causes this code to fail to compile. I'm not sure why...
traceM ("Four is: " <> show four)
pure (four + 8)
log $ "Value is: " <> show value
-- Box's type class instances
instance monadBox :: Monad Box -- instance needed for some reason!
instance functorBox :: Functor Box where
map f (Box a) = Box (f a)
instance applyBox :: Apply Box where
apply (Box f) (Box a) = Box (f a)
instance applicativeBox :: Applicative Box where
pure a = Box a
instance bindBox :: Bind Box where
bind (Box a) f = f a