PureScript - 模式匹配未知长度的数组

时间:2017-02-25 00:08:57

标签: purescript

有没有办法在PureScript中模式匹配未知长度的数组?作为一个例子,我在Haskell中使用List来实现这一点:

addFirstTwo :: (Num a) => [a] -> a
addFirstTwo (x:y:_) = x + y

我在PureScript中尝试过类似的东西(使用Array a代替[a]),但收到了以下错误:

  

运算符Data.Array。(:)不能在模式中使用,因为它是函数Data.Array.cons的别名。   只能在模式中使用数据构造函数的别名。

我知道我可以在PureScript中使用List而不是Arrays,但是我希望模式匹配数组。阅读Array pattern matching section of PureScript by Example后我没看到怎么做。

1 个答案:

答案 0 :(得分:10)

数组缺点模式早已从语言中删除。您可以使用uncons中的Data.Array代替,例如:

case uncons xs of
  Just {head: x, tail} ->
    case uncons tail of
      Just {head: y, tail: _} -> x + y
      Nothing -> 0
  Nothing -> 0

但要注意unconsΘ(n)

或者,您可以使用take中的Data.Array

case take 2 xs of
  [a, b] -> a + b
  _ -> 0

takeΘ(min(n,m))(在这种情况下,m = 2)。

甚至来自(!!)的{​​{1}}:

Data.Array

通常,列表比数组更令人愉快。

相关问题