tags:

views:

88

answers:

3

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

+2  A: 

You could use GHC's ReadP.

SamB
+6  A: 

This sounds like something better suited to a parser; Parsec is a powerful Haskell parser combinator library, which I would recommend.

Antal S-Z
+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