【问题标题】:PureScript - Pattern match arrays of unknown lengthPureScript - 未知长度的模式匹配数组
【发布时间】:2017-07-15 23:26:18
【问题描述】:

有没有办法在 PureScript 中对未知长度的数组进行模式匹配?例如,下面是我在 Haskell 中使用 List 的方法:

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

我在 PureScript 中尝试过类似的操作(使用 Array a 而不是 [a]),但出现以下错误:

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

我知道我可以在 PureScript 中使用 Lists 而不是数组,但我想对数组进行模式匹配。看了Array pattern matching section of PureScript by Example之后没看到怎么做。

【问题讨论】:

    标签: purescript


    【解决方案1】:

    数组 cons 模式很久以前就从语言中删除了。您可以改用 Data.Array 中的 uncons,如下所示:

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

    但要注意unconsΘ(n)

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

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

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

    甚至来自Data.Array(!!)

    case xs !! 0, xs !! 1 of
      Just x, Just y -> x + y
      _, _ -> 0
    

    一般来说,列表比数组更易于使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 2019-05-01
      • 2013-08-19
      • 2016-09-04
      • 1970-01-01
      • 2011-08-23
      相关资源
      最近更新 更多