[project @ 2005-10-20 10:58:44 by malcolm]
authormalcolm <unknown>
Thu, 20 Oct 2005 10:58:44 +0000 (10:58 +0000)
committermalcolm <unknown>
Thu, 20 Oct 2005 10:58:44 +0000 (10:58 +0000)
Instance of Read for Map, from Georg Martius.

Data/Map.hs

index f916606..7666030 100644 (file)
@@ -28,7 +28,7 @@
 
 module Data.Map  ( 
             -- * Map type
-              Map          -- instance Eq,Show
+              Map          -- instance Eq,Show,Read
 
             -- * Operators
             , (!), (\\)
@@ -1305,6 +1305,28 @@ instance Functor (Map k) where
   fmap f m  = map f m
 
 {--------------------------------------------------------------------
+  Read
+--------------------------------------------------------------------}
+instance (Ord k, Read k, Read e) => Read (Map k e) where
+    readsPrec _ = readParen False $ \ r ->
+                  [(fromList xs,t) | ("{",s) <- lex r
+                                   , (xs,t)  <- readl s]
+        where readl s  = [([],t)   | ("}",t) <- lex s] ++
+                         [(x:xs,u) | (x,t)   <- readPair s
+                                   , (xs,u)  <- readl' t]
+              readl' s = [([],t)   | ("}",t) <- lex s] ++
+                         [(x:xs,v) | (",",t) <- lex s
+                                   , (x,u)   <- readPair t
+                                   , (xs,v)  <- readl' u]
+
+-- parses a pair of things with the syntax a:=b
+readPair :: (Read a, Read b) => ReadS (a,b)
+readPair s = do (a, ct1)    <- reads s
+                (":=", ct2) <- lex ct1
+                (b, ct3)    <- reads ct2
+                return ((a,b), ct3)
+
+{--------------------------------------------------------------------
   Show
 --------------------------------------------------------------------}
 instance (Show k, Show a) => Show (Map k a) where