我尝试为ADT定义一个show实例,但是我收到了错误Argument list lengths differ in declaration show
。如何在不使用Generic
的情况下完成此工作?
data Route = Home | Users String | User Int | NotFound String
instance showRoute :: Show Route where
show Home = "Home"
show Users str = "Users"
show User i = "User"
show NotFound str = "404"
答案 0 :(得分:2)
您必须在括号中包含带参数的构造函数。尝试这样的事情:
instance showRoute :: Show Route where
show Home = "Home"
show (Users str) = "Users"
show (User i) = "User"
show (NotFound str) = "404"
Show
相关方面注意:
您还可以使用Show
为这种简单类型派生purescript-generic-reps
个实例,但您必须先为Generic
派生实例:
import Data.Generic.Rep (class Generic)
import Data.Generic.Rep.Show (genericShow)
data Route = Home | Users String | User Int | NotFound String
derive instance genericRoute :: Generic Route _
instance showRoute :: Show Route where
show = genericShow
我制作了简单的代码段,以便您可以在try.purescript.org上播放
甚至可以混合使用这两种方法:
instance showRoute :: Show Route where
show (Users u) = "CusomUsersShow " <> u
show u = genericShow u
出于调试目的,您始终可以使用traceAny
中的traceAnyA
(spy
,purescript-debug
等)。就个人而言,我只在必须时(例如Show
强迫)编写purescript-test-unit
个实例。
目前,您无法轻松地为具有嵌套记录的类型派生实例,因此它对我来说是额外的阻止程序; - )