Skip to content

Instantly share code, notes, and snippets.

@kayvank
Created July 17, 2025 20:09
Show Gist options
  • Select an option

  • Save kayvank/60b52886709b78a1e99c551a7d0331be to your computer and use it in GitHub Desktop.

Select an option

Save kayvank/60b52886709b78a1e99c551a7d0331be to your computer and use it in GitHub Desktop.
State Monad to Lazy Stream
#!/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-"
@kayvank
Copy link
Author

kayvank commented Jul 17, 2025

nix-haskell script.
to execute:

chmod 755 ./stateMonadToLazyStream.hs
./stateMonadToLazyStream

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment