Hi, I am writing a custom read function for one of the data types in my module. For eg, when I do read "(1 + 1)" :: Data
, I want it to return Plus 1 1
. My data declaration is data Data = Plus Int Int
. Thanks
views:
88answers:
3
+3
A:
I'd like to second the notion of using a parser. However, if you absolutely have to use a pattern-matching, go like this:
import Data.List
data Expr = Plus Int Int | Minus Int Int deriving Show
test = [ myRead "(1 + 1)", myRead "(2-1)" ]
myRead = match . lexer
where
match ["(",a,"+",b,")"] = Plus (read a) (read b)
match ["(",a,"-",b,")"] = Minus (read a) (read b)
match garbage = error $ "Cannot parse " ++ show garbage
lexer = unfoldr next_lexeme
where
next_lexeme "" = Nothing
next_lexeme str = Just $ head $ lex str
ADEpt
2010-04-02 07:35:52