如何巧妙地解构嵌套在记录中的新类型?

How to neatly deconstruct newtypes nested into records?

我使用 newtype 作为记录的字段,在 "parent" 类型上进行模式匹配以提取嵌套值很麻烦:

newtype CityName = CityName String
newtype City = City {
  name :: CityName
}
instance showCity :: Show City where
  show (City { name }) = case name of (CityName cn) -> "City(" <> cn <> ")"

我可以解构 "parent" 类型,但随后我使用另一种模式匹配来提取包装的字符串 - 即使 newtype 只有一个数据构造函数。将整个类型解构为一种模式会更方便。

这可能吗?如果是这样,我无法获得正确的语法。我尝试了 show (City { name :: (CityName cn) }) = cn 之类的东西,但它给了我语法错误。 PureScript by Example 也没有帮助我,但也许有更简洁的方法来做我想做的事?

你试的几乎是对的,但是模式匹配记录时只需要一个冒号:

instance showCity :: Show City where
  show (City { name: CityName cn }) = "City(" <> cn <> ")"

双冒号只用于注释类型,值级别的东西总是使用单冒号。