Commits

Aleksey Khudyakov committed f15ff79

Add Nothing handling in reading from string

Comments (0)

Files changed (2)

Data/Histogram.hs

                       ) where
 
 import Control.Arrow ((***))
+import Control.Monad (ap)
 import Data.Array.Vector
 import Text.Read
 import Text.ParserCombinators.ReadPrec (readPrec_to_S)
               -> UArr a
               -> Histogram bin a
 
+
 instance (Show a, Show (BinValue bin), Show bin) => Show (Histogram bin a) where
     show h@(Histogram bin uo _) = "# Histogram\n" ++ showUO uo ++ show bin ++
                                   (unlines $ map showT $ asList h)
 histHeader :: (Read bin, Read a, Bin bin, UA a) => ReadPrec (UArr a -> Histogram bin a)
 histHeader = do
   keyword "Histogram"
-  -- FIXME: will fail for Nothing 
-  u   <- value "Underflows"
-  o   <- value "Overflows"
+  u   <- maybeValue "Underflows"
+  o   <- maybeValue "Overflows"
   bin <- readPrec
-  return $ Histogram bin (Just (u,o))
+  return $ Histogram bin ((,) `fmap` u `ap` o)
 
 -- | Convert String to histogram. Histogram do not have Read instance
 --   because of slowness of ReadP

Data/Histogram/Parse.hs

 module Data.Histogram.Parse ( ws
                             , eol
                             , value
+                            , maybeValue
                             , keyword
                             ) where
 
 import Text.Read
-import Text.ParserCombinators.ReadP
+import Text.ParserCombinators.ReadP    (ReadP, many, satisfy, char, string)
 import Text.ParserCombinators.ReadPrec
 
 -- Whitespaces
 key :: String -> ReadP String
 key s = char '#' >> ws >> string s 
 
+
+getVal :: Read a => ReadPrec a
+getVal = do x <- readPrec
+            lift eol 
+            return x
+
 -- Key value pair
 value :: Read a => String -> ReadPrec a
-value str = do 
-  lift $ key str >> eq
-  x <- readPrec
-  lift $ eol
-  return x
+value str = do lift $ key str >> eq
+               getVal
+
+-- Return optional value
+maybeValue :: Read a => String -> ReadPrec (Maybe a)
+maybeValue str = do lift $ key str >> eq
+                    (lift $ ws >> eol >> return Nothing) <++ (Just `fmap` getVal)
 
 -- Keyword
 keyword :: String -> ReadPrec ()