开发者

Pattern matching for custom read function

开发者 https://www.devze.com 2022-12-25 04:14 出处:网络
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 da开发者_开发问答ta Data =

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 da开发者_开发问答ta Data = Plus Int Int. Thanks


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


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


You could use GHC's ReadP.

0

精彩评论

暂无评论...
验证码 换一张
取 消