纯脚本中的模式匹配

Pattern matching in purescript

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

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

returns:

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?)
fromSingleton :: forall a. a -> Array a -> a
fromSingleton def x = case Array.uncons x of
  Nothing -> def
  Just { head } -> head

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