foldl Implementation with Runtime Errors
Solution 1:
There's actually no good reason why not to do this. Many of the functions in Haskell's prelude like head
, tail
, init
, and many many others fail unnecessarily.
It would be much nicer for them to explicitly note their failure in the types, but that's unfortunately just not what happened when Prelude was standardized and we can't very well change several core functions like head
!
Nowadays I recommend simply not using many of these functions and opting for pattern matching, or Gabriel Gonzalez's errors library which provides alternate versions of prelude's partial functions which fail properly.
For example in Control.Error.Safe
there's
foldl1Err :: e -> (a -> a -> a) -> [a] -> Either e a
and errors also exports safe, a similar library with Maybe
's which has the function
foldl1May :: (a -> a -> a) -> [a] -> Maybe a
exactly like what you wanted :)