Learn You a Haskell explains foldl1
:
The foldl1 and foldr1 functions work much like foldl and foldr, only
you don't need to provide them with an explicit starting value. They
assume the first (or last) element of the list to be the starting
value and then start the fold with the element next to it. ...
Because they depend on the lists they fold up having at least one
element, they cause runtime errors if called with empty lists
I figured its implementation is, more or less, the following:
foldl1' :: (a -> a -> a) -> [a] -> a
foldl1' f ys = foldl f (head ys) (tail ys)
But, this potential run-time error troubles me.
Why not implement foldlOption
in the following way?
foldlOption :: (a -> a -> a) -> [a] -> Maybe a
foldlOption f [] = Nothing
foldlOption f ys = Just (foldl f (head ys) (tail ys))
REPL
*Main> foldlOption (acc elem -> if (elem > acc) then elem else acc) []
Nothing
-- find max
*Main> foldlOption (acc elem -> if (elem > acc) then elem else acc) [1,100,2,3]
Just 100
EDITED
Updated foldl1
's and foldlOption
's definitions to use tail ys
as the last argument to foldl
, not ys
per Lee Duhem's correction. .
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…