public
Created

  • Download Gist
gistfile1.hs
Haskell
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.