在 Haskell 中加入 NonEmpty 类型

Joining NonEmpty types in Haskell

提问人:Marco Bazzani 提问时间:8/12/2023 更新时间:8/12/2023 访问量:60

问:

如果我有两个类型为 (NonEmpty a) 的通用对象,我如何将这两个对象联接到一个新的 (NonEmpty a) 中,就像使用列表一样?++

我期望能够做以下事情

let x = 1:|[]
let y = 2:|[]
x ++ y

但是,这给了我以下错误

<interactive>:65:1: error:
    • Couldn't match expected type: [a]
                  with actual type: NonEmpty a0
    • In the first argument of ‘(++)’, namely ‘x’
      In the expression: x ++ y
      In an equation for ‘it’: it = x ++ y
    • Relevant bindings include it :: [a] (bound at <interactive>:65:1)

<interactive>:65:6: error:
    • Couldn't match expected type: [a]
                  with actual type: NonEmpty a1
    • In the second argument of ‘(++)’, namely ‘y’
      In the expression: x ++ y
      In an equation for ‘it’: it = x ++ y
    • Relevant bindings include it :: [a] (bound at <interactive>:65:1)

这告诉我的是,运算符不是为 NonEmpty 类型定义的。是否有类似的运算符可以做同样的事情?++

列表 哈斯克尔

评论

6赞 Iceland_jack 8/12/2023
NonEmpty 有一个 Semigroup 实例(它们是自由的 semigroup),因此您可以使用 Semigroup 方法追加它们:x <> y

答: 暂无答案