foldl Implementation with Runtime Errors

后端 未结 1 1461
梦毁少年i
梦毁少年i 2020-11-30 14:36

Learn You a Haskell explains foldl1:

The foldl1 and foldr1 functions work much like foldl and foldr, only you don\'t need to provide th

相关标签:
1条回答
  • 2020-11-30 14:37

    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 :)

    0 讨论(0)
提交回复
热议问题