1

我的代码目前看起来像这样。它应该在事先给我们的正则表达式定义中显示可能的第一个符号。我应该把这些打印出来作为一个列表。例如,如果答案应该是 [1,2],它会出现 [1,2] 但当答案应该是 ['1','2'] 时,它会出现“12”或当它应该是 ['a', 'b'] 时,它会出现“ab”。我究竟做错了什么?

data RE a         -- regular expressions over an alphabet defined by 'a'
    = Empty          -- empty regular expression
    | Sym a          -- match the given symbol
    | RE a :+: RE a  -- concatenation of two regular expressions
    | RE a :|: RE a  -- choice between two regular expressions
    | Rep (RE a)     -- zero or more repetitions of a regular expression
    | Rep1 (RE a)    -- one or more repetitions of a regular expression
    deriving (Show)

firstMatches :: RE a -> [a]
firstMatches Empty = []
firstMatches (Sym a)= a:list
firstMatches(Rep(a))=firstMatches a
firstMatches(Rep1(a))=firstMatches a
firstMatches (Empty :+: b)= firstMatches b
firstMatches (a :+: _) = firstMatches a
firstMatches (a :|: b)= firstMatches a ++ firstMatches b
4

1 回答 1

2

你没有做错什么。

String是 的类型同义词[Char],因此如果您尝试打印 a [Char],它将打印为String. 这有点特殊,可能有点奇怪。

Show是用于将事物打印为字符串的类型类。的定义Show是这样的:

class Show a where
    showsPrec :: Int -> a -> ShowS
    show      :: a -> String
    showList  :: [a] -> ShowS

showList功能是可选的。该文档指出:

提供该方法showList是为了允许程序员提供一种显示值列表的特殊方式。例如,这由类型的预定义Show实例使用Char,其中类型的值String应显示在双引号中,而不是在方括号之间。

因此,如果您定义一个新类型并实例化Show,您可以选择show为您的类型列表定义一种特殊方式,与通常显示的方式分开,也与通常显示列表的方式分开。Char利用这一点,因为 a [Char](或等效的 a String)用双引号而不是Char值列表显示。


我想不出一种方法让它使用默认show的 a [Char]。我不认为有一个。一种解决方法可能是创建一个使用默认实现的newtype包装,但这在这里似乎不合适。CharShowshowList

如果这是家庭作业,我希望评分者已经知道这一点,我严重怀疑你会因此而被扣分,特别是因为问题似乎根本不存在show

于 2018-11-10T00:47:36.867 回答