【问题标题】:Use records update syntax for newtype使用新类型的记录更新语法
【发布时间】:2022-08-17 02:24:55
【问题描述】:

以前我有这种类型:

type Directions =
  { top    :: Boolean
  , right  :: Boolean
  , bottom :: Boolean
  , left   :: Boolean
  }

对于这种类型,我有这个功能

empty = { top: false, right: false, bottom: false, left: false}

withLeft = empty { left = true }

我想将Directions 转换为newtype,但我也想使用与withLeft 相同的语法,像这样...

newtype Directions = Directions
  { top    :: Boolean
  , right  :: Boolean
  , bottom :: Boolean
  , left   :: Boolean
  }

empty = Directions { top: false, right: false, bottom: false, left: false}

withLeft = empty { left = true }

...但这不起作用。我该怎么做?

  • 不是 100% 确定,但我认为您必须手动打开/包装:withLeft = let Directions empty\' = empty in Directions empty\' { left = true }
  • @Dogbert 看来您是对的,我通过使用与您的empty\' 相同的默认记录找到了类似的解决方案。

标签: purescript


【解决方案1】:

您不能将记录更新语法与Directions 一起使用,因为它不是记录。但是你可以接近一些。

例如,您可以利用部分应用记录本身丢失的记录更新。语法是_ { x = y },它是\r -> r { x = y } 的简写。

有了这个,你可以让自己成为一个“更新路线”功能:

type DirectionsR = { top: false, right: false, bottom: false, left: false}
newtype Directions = Directions DirectionsR

ud :: (DirectionsR -> DirectionsR) -> Direction -> Direction
ud f (Directions d) = Directions (f d)

接着:

withLeft = empty # ud _ { left = true }

顺便说一句,ud 函数也可以用over 编码:

ud = over Directions

当然你也可以直接在withLeft的正文中使用over

withLeft = empty # over Directions _ { left = true }

但在我看来,这有点太冗长了。

【讨论】:

    猜你喜欢
    • 2012-11-21
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多