Skip to content

Commit 7920cd5

Browse files
committed
add Haskell snippet for State monad to manage mutable state
1 parent f2ba64a commit 7920cd5

File tree

1 file changed

+25
-0
lines changed

1 file changed

+25
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
---
2+
title: State Monad
3+
description: Managing mutable state using the State monad.
4+
author: ACR1209
5+
tags: haskell, monads, state, state-management
6+
---
7+
8+
```hs
9+
import Control.Monad.State
10+
11+
increment :: State Int Int
12+
increment = do
13+
count <- get
14+
put (count + 1)
15+
return count
16+
17+
main :: IO ()
18+
main = do
19+
let (res1, intermediateState) = runState increment 0
20+
print res1 -- Output: 0
21+
let (result, finalState) = runState increment intermediateState
22+
print result -- Output: 1
23+
print finalState -- Output: 2
24+
25+
```

0 commit comments

Comments
 (0)