Created
July 17, 2025 20:09
-
-
Save kayvank/60b52886709b78a1e99c551a7d0331be to your computer and use it in GitHub Desktop.
State Monad to Lazy Stream
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/usr/bin/env nix-shell | |
| #!nix-shell --pure -p "haskellPackages.ghcWithPackages(pkgs:[pkgs.mtl pkgs.stm])" -i runghc | |
| {- | | |
| state monad to lazy stream | |
| -} | |
| {-# LANGUAGE LambdaCase #-} | |
| import Control.Monad.State.Lazy(State, modify, runState, gets) | |
| stateToList :: State s a -> s -> [a] | |
| stateToList st s = case runState st s of {(x, s') -> x : stateToList st s'} | |
| type Node = Int | |
| data AlgState = AlgState | |
| { | |
| counter :: Int | |
| , visited :: [Node] | |
| } deriving Show | |
| travelM :: State AlgState Int | |
| travelM = do | |
| c <- gets counter | |
| modify (\s -> s {visited = c:visited s}) | |
| visited' <- gets visited | |
| modify (\s -> s {counter=c+(length visited')}) | |
| pure c | |
| stream = stateToList travelM (AlgState 0 []) | |
| main :: IO () | |
| main = do | |
| print "StateMonad to LazyStream" | |
| print $ take 10 $ stream | |
| print "-End-" |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
nix-haskell script.
to execute: