枚举类型的自定义派生(读取,显示)

Pub*_*bby 3 haskell template-haskell deriving

假设我有这种枚举类型:

data TVShow = BobsBurgers | MrRobot | BatmanTAS
Run Code Online (Sandbox Code Playgroud)

我想定义为实例Read,并Show与以下行为:

show BobsBurgers = "Bob's Burgers"
show MrRobot = "Mr. Robot"
show BatmanTAS = "Batman: The Animated Series"

read "Bob's Burgers" = BobsBurgers
read "Mr. Robot" = MrRobot
read "Batman: The Animated Series" = BatmanTAS
Run Code Online (Sandbox Code Playgroud)

有很多在这些定义重复的,所以我想每种类型的构造函数的字符串相关联,然后生成ShowRead自动从这些关联.这样的事情可能吗?

Dan*_*ner 7

论文" 可逆语法描述:统一解析和漂亮打印"描述了一种特别惯用的解决方案.您的示例如下所示,使用基于该论文的invertible语法包:

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: The Animated Series"

runParser (Parser p) = p
instance Read TVShow where readsPrec _ = runParser tvShow
instance Show TVShow where show = fromJust . print tvShow
Run Code Online (Sandbox Code Playgroud)

这被设计为可扩展到比简单枚举更令人兴奋的类型.