【发布时间】:2017-05-03 14:43:06
【问题描述】:
我通过将数据实现为Enum 来尝试以下代码。
而且,我有一个问题,只是将Enum 替换为newtype。
这是我的测试代码。
newtype Fruit = Fruit Int deriving (Eq)
apple = Fruit 0
banana = Fruit 1
grape = Fruit 2
orange = Fruit 3
instance Show Fruit where
show apple = "Apple"
show banana = "Banana"
show grape = "Grape"
show orange = "Orange"
show _ = "Fruit"
test =
map show [apple, banana, grape, orange, (Fruit 5)]
我预计评估的test 将是["Apple","Banana","Grape","Orange","Fruit"],但它是["Apple","Apple","Apple","Apple","Apple"]
我认为 it 变量可能无法很好地与模式匹配一起使用,但我又通过case 尝试了一次,例如:
-- Fails: everything is "Apple"
instance Show Fruit where
show g = case g of
apple -> "Apple"
banana -> "Banana"
grape -> "Grape"
orange -> "Orange"
_ -> "Fruit"
为了确认我的临时代码,我再次尝试了下一个代码。
-- Fails: Works only for apple/banana. Variable does not work!
instance Show Fruit where
show (Fruit 0) = "Apple"
show (Fruit 1) = "Banana"
show grape = "Grape"
show orange = "Orange"
show _ = "Fruit"
我可以得到["Apple","Banana","Grape","Grape","Grape"]
好吧,我可以用Enum 编写代码来实现,但我只是想了解为什么这些代码不能正常工作?
【问题讨论】:
-
您应该使用
data而不是newtype吗? -
旁注:
show grape和show orange等同于show _,因此模式重叠。编译器不会将橙色与上面的定义匹配,而是将其视为本地标识符。 -
如果您只使用静态定义的水果,您应该真正使用 sum 类型来表示您的数据,而不是使用
Int周围的包装器。例如:data Fruit = Apple | Banana | Grape | Orange deriving Eq