Created
July 4, 2012 14:33
-
-
Save benma/3047673 to your computer and use it in GitHub Desktop.
This file contains 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
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