Skip to content

Instantly share code, notes, and snippets.

@benma
Created July 4, 2012 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benma/3047673 to your computer and use it in GitHub Desktop.
Save benma/3047673 to your computer and use it in GitHub Desktop.
import Control.Monad.RWS
import Data.Map
import qualified Data.Map as Map
type Knot k s a = RWS k k s a
tie :: Knot k s a -> s -> (a, s, k)
tie knot s0 =
let (a, s1, k) = runRWS knot k s0 -- this is fucking interesting
in (a, s1, k)
data Node = Node {
value :: Int,
next :: Node
}
data ParserState = ParserState {
_map :: Map Int Node,
remaining :: [(Int, Int)]
}
type NodeParser a = Knot (Map Int Node) ParserState a
parse :: NodeParser ()
parse = do
s <- get
case remaining s of
[] -> return ()
((val, ref) : rest) -> do
let mm = _map s
put $ ParserState (Map.insert val (Node val $ mm ! ref) mm) rest
parse
-- example :: Node
example =
let (_, s, _) = tie parse $ ParserState Map.empty [(10, 2), (2, 3), (3, 10)]
in _map s Map.! 10
main = putStrLn $ show $ value $ next example
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment