parsing - How exactly is readsPrec supposed to work? -
i newbie haskell. making read
instance of custom type, decimalfp
:
data integral => decimalfp = decimalfp {infprec :: bool, digits :: a, exp :: a}
which used decimal floating-point type specific significant figures.
i'm unsure how readsproc
works, these issues:
1. why return type list?
when this:
prelude> readsprec 0 "21345 1223 -5" :: [(int, string)]
i expected this:
[(21345," 1223 -5"),(1223," -5"),(-5,"")]
but actual result just:
[(21345," 1223 -5")]
so when readsprec
return multiple elements?
2. return type seems biased?
this works expected:
prelude> readsprec 0 "245e-3" :: [(float, string)]
it outputs [(0.245,"")]
. when this:
prelude> readsprec 0 "245e-3" :: [(int, string)]
it outputs []
. expected [(245,"e-3")]
. why happen?
3. first argument do?
i know has operator precedence, exactly?
edit: besides, here completed read
instance of decimalfp
:
instance (integral a) => read (decimalfp a) readsprec p cs = let (bigdigits, rem1) = parsesigned cs let (_, rem1') = parsediscard "." rem1 let (smalldigits, rem2) = parseunsigned rem1' let (succ, rem2') = parsediscard "ee" rem2 let (expdigits, rem3) = if succ parsesigned rem2' else ("0", rem2') let digitshift = frominteger $ tointeger $ length smalldigits digit <- map (frominteger . fst) (readsprec p $ bigdigits ++ smalldigits :: [(integer, string)]) exp <- map (frominteger . fst) (readsprec p expdigits :: [(integer, string)]) return (decimalfp false digit $ exp - digitshift, rem3) parseunsigned, parsesigned :: string -> (string, string) parseunsigned = span (`elem` "0123456789") parsesigned str@(c:cs) = if c `elem` "-0123456789" let (digits, rem) = parseunsigned cs in (c:digits, rem) else ("", str) parsesigned _ = ("", "") parsediscard :: string -> string -> (bool, string) parsediscard s1 str@(c:cs) = let succ = c `elem` s1 in (succ, if succ cs else str) parsediscard _ _ = (false, "")
Comments
Post a Comment