We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 63ad862 commit f2ba64aCopy full SHA for f2ba64a
snippets/haskell/monads/writer-monad.md
@@ -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