How can I implement head
or singleton
function in purescript by pattern matching? The problem is that the compiler requires the explicit definition of the broadest pattern, but I can't generate a default value for a type that I don't know.
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.
But this proposal looks dummy, I can't add:
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
This should work. Your original version covered all cases for the first argument, but for the second argument, you only covered the case of empty array and singleton array.