Skip to content

Commit f2ba64a

Browse files
committed
add Haskell snippet for Writer monad to accumulate logs alongside computations
1 parent 63ad862 commit f2ba64a

File tree

1 file changed

+23
-0
lines changed

1 file changed

+23
-0
lines changed
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
---
2+
title: Writer Monad
3+
description: Using the Writer monad to accumulate logs or other outputs alongside a computation.
4+
author: ACR1209
5+
tags: haskell, monads, writer, logs
6+
---
7+
8+
```hs
9+
import Control.Monad.Writer
10+
11+
addAndLog :: Int -> Int -> Writer [String] Int
12+
addAndLog x y = do
13+
tell ["Adding " ++ show x ++ " and " ++ show y]
14+
return (x + y)
15+
16+
main :: IO ()
17+
main = do
18+
let (result, logs) = runWriter $ do
19+
res1 <- addAndLog 3 5
20+
addAndLog res1 1
21+
print result -- Output: 9
22+
print logs -- Output: ["Adding 3 and 5", "Adding 8 and 1"]
23+
```

0 commit comments

Comments
 (0)