haskell - Custom deriving(Read,Show) for enum type -


let's have enumeration type:

data tvshow = bobsburgers | mrrobot | batmantas 

and want define instances read , show following behavior:

show bobsburgers = "bob's burgers" show mrrobot = "mr. robot" show batmantas = "batman: animated series"  read "bob's burgers" = bobsburgers read "mr. robot" = mrrobot read "batman: animated series" = batmantas 

there lots of repetition in these definitions, , i'd associate each type constructor string , generate show , read automatically associations. such thing possible?

the paper invertible syntax descriptions: unifying parsing , pretty printing describes 1 particularly idiomatic solution. example looks this, using invertible-syntax package based on paper:

import prelude hiding (applicative(..), print) import data.maybe (fromjust) import text.syntax import text.syntax.parser.naive import text.syntax.printer.naive  data tvshow = bobsburgers | mrrobot | batmantas deriving (eq, ord)  tvshow :: syntax f => f tvshow tvshow =  pure bobsburgers <* text "bob's burgers"       <|> pure mrrobot     <* text "mr. robot"       <|> pure batmantas   <* text "batman: animated series"  runparser (parser p) = p instance read tvshow readsprec _ = runparser tvshow instance show tvshow show = fromjust . print tvshow 

this designed extensible types more exciting simple enumerations, well.


Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -