如何通过模式匹配在purescript中实现head
或singleton
功能?问题在于编译器需要对最广泛的模式进行显式定义,但是我无法为我不知道的类型生成默认值。
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?)
fromSingleton :: forall a. a -> Array a -> a
fromSingleton def x = case Array.uncons x of
Nothing -> def
Just { head } -> head
这应该有效。原始版本涵盖了第一个参数的所有情况,但是对于第二个参数,您仅覆盖了空数组和单例数组的情况。