为ADT定义show instance

时间:2017-12-13 15:56:17

标签: purescript

我尝试为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"

1 个答案:

答案 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中的traceAnyAspypurescript-debug等)。就个人而言,我只在必须时(例如Show强迫)编写purescript-test-unit个实例。 目前,您无法轻松地为具有嵌套记录的类型派生实例,因此它对我来说是额外的阻止程序; - )