given the following function
maxInt :: Array Number -> Int
maxInt xs = fromMaybe 0 $ join $ fromNumber <$> maximum xs
maxInt [ 2.0, 4.0, 1.0, 5.0 ] => 5
Is there some a more elegant way to do this? There is a lot of stripping away Maybe
s
given the following function
maxInt :: Array Number -> Int
maxInt xs = fromMaybe 0 $ join $ fromNumber <$> maximum xs
maxInt [ 2.0, 4.0, 1.0, 5.0 ] => 5
Is there some a more elegant way to do this? There is a lot of stripping away Maybe
s
Apply fromNumber
to the entire input first, then take the maximum of that list. This way, all invalid values are converted to Nothing
first, which maximum
will ignore.
maxInt = fromMaybe 0 . maximum . (map fromNumber)
(This works because Ord a => Maybe a
is an instance of Ord
; Nothing
is less than any Just
value, and Just
values are ordered by the underlying value.)
This also fixes a potential bug, if fromNumber (maximum xs) == Nothing
. In that case, maxInt
would return 0, even if there is some slightly smaller value y
such that fromNumber y
is not Nothing
.
Are you sure you want to handle that with a default case of 0? If so, you're looking for maxInt xs = fromMaybe 0 $ fromNumber =<< maximum xs
. If not, keep the Maybe around and do it like maxInt = fromNumber <=< maximum
.