【问题标题】:Pattern matching in purescriptpurescript 中的模式匹配
【发布时间】:2019-10-08 07:55:48
【问题描述】:

如何通过模式匹配在纯脚本中实现headsingleton 函数?问题是编译器需要明确定义最广泛的模式,但我无法为我不知道的类型生成默认值。

fromSingleton :: forall a. a -> Array a -> a 
fromSingleton _   [x] = x
fromSingleton def []    = def

返回:

A case expression could not be determined to cover all inputs.
  The following additional cases are required to cover all inputs:

    _ _

  Alternatively, add a Partial constraint to the type of the enclosing value.

但是这个提议看起来很虚,我不能补充:

fromSingleton _ _     = ??? (a -- is any type, how can I implement default for it?)

【问题讨论】:

    标签: purescript


    【解决方案1】:
    fromSingleton :: forall a. a -> Array a -> a
    fromSingleton def x = case Array.uncons x of
      Nothing -> def
      Just { head } -> head
    

    这应该可以。您的原始版本涵盖了第一个参数的所有情况,但是对于第二个参数,您只涵盖了空数组和单例数组的情况。

    【讨论】:

      猜你喜欢
      • 2017-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-11
      • 1970-01-01
      • 2011-02-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多