[Haskell-cafe] A probably-stupid question about a Prelude
implementation.
Dougal Stanton
ithika at gmail.com
Fri Jun 22 11:48:28 EDT 2007
On 22/06/07, Michael T. Richter <ttmrichter at gmail.com> wrote:
>
> So, I'm now going over the code in the 'Report with a fine-toothed comb because a) I'm actually able to read it now pretty fluently and b) I want to know what's there in detail for a project I'm starting. I stumbled across this code:
>
>
> any :: (a -> Bool) -> [a] -> Bool
> any p = or . map p
>
> or :: [Bool] -> Bool
> or = foldr (||) False
>
> Now I see how this works and it's all elegant and clear and all that. But I have two nagging problems with it (that are likely related):
>
> Using foldr means I'll be traversing the whole list no matter what. This implies (perhaps for a good reason) that it can only work on a finite list.
> I don't see any early bale-out semantics. The way I read this it's going to expand a whole list of n and perform n comparisons (including the one with the provided False).
Well, try it:
Prelude> any (>10) [1..]
True
By way of contrast, this (doesn't) work as you expected:
Prelude> let any' p = foldl (||) False . map p
Prelude> any' (>10) [1..]
^C
Interrupted.
A left fold will keep on going with an infinite list in this case.
D.
More information about the Haskell-Cafe
mailing list