"fold": a replacement for "reduce"
bearophile
bearophileHUGS at lycos.com
Tue Mar 25 11:24:33 PDT 2014
monarch_dodra:
> I'm taking this naming-changing event as an opportunity to
> "cleanup" reduce too. One thing that gets on my nerves is that
> "range.reduce()" is not nothrow, because it throws an exception
> if the range is empty.
>
> I think this is wrong. popping an empty range is an *Error*,
> and should be validated by the programmer. Because of this, it
> is currently not possible to use "reduce(range)" in nothrow
> context.
This Haskell library shows one way Haskellers use to face similar
problems:
http://hackage.haskell.org/package/safe-0.3.4/docs/Safe.html
Every function that could have similar problems is present in
four forms, with the "Note", "Def", "May" and "Safe" suffixes.
An example with the standard Haskell function "tail", that is
similar to dropOne of std.range (skips the first and returns the
rest. The problem is when the input list is empty):
tailDef :: [a] -> [a] -> [a]
tailDef [12] [] = [12]
tailDef [12] [1,3,4] = [3,4]
tailMay :: [a] -> Maybe [a]
tailMay [] = Nothing
tailMay [1,3,4] = Just [3,4]
tailNote :: String -> [a] -> [a]
tail "help me" [] = error "Pattern match failure, tail [], help
me"
tail "help me" [1,3,4] = [3,4]
tailSafe :: [a] -> [a]
tailSafe [] = []
tailSafe [1,3,4] = [3,4]
Bye,
bearophile
More information about the Digitalmars-d
mailing list