fromMaybe
is a function that ‘extracts’ a purescript value that’s wrapped in a Maybe
.
Here’s how we might implement this naively:
fromMaybe :: forall a. Maybe a -> a
fromMaybe (Just value) = value {- value has type a -}
fromMaybe Nothing = {- Uhm? How to return something of type a? -}
Right now, this is a partial function. It can’t cover all its inputs. The problem is that we don’t have anything to return in the case where Maybe a
doesn’t have a value.
One solution is to upgrade this to take a default value with the right type.
fromMaybe :: forall a. a -> Maybe a -> a
fromMaybe fallback (Just value) = value {- value has type a -}
fromMaybe fallback Nothing = fallback {- fallback has type a -}
Back to your code. Consider the types here:
fromMaybe [] (head arr)
[]
is an Array
head arr
is Maybe Int
You’re asking fromMaybe
to return an Int, and if it can’t, to return an empty array.
That would type something like this:
fromMaybe :: forall a b. a -> Maybe b -> Either a b
fromMaybe fallback (Just value) = Right value {- value has type b -}
fromMaybe fallback Nothing = Left fallback {- fallback has type a -}
arr :: Array Int
arr = ...
firstValue :: forall a. Either (Array a) Int
firstValue = fromMaybe [] (head arr)
Instead of the one we created here, fromMaybe
has this type signature:
fromMaybe :: forall a. a -> Maybe a -> a
Instead of having two types (a and b), we have only one. Which tells us that the default value and the value being wrapped in the Maybe
must have the same type.
[]
and Int
do not have the same type.
Instead, you could try something like:
fromMaybe 0 (head arr)
In this case, (0 :: Int)
and ((head arr) :: Maybe Int)
have types that work with fromMaybe
.