[Haskell-cafe] A probably-stupid question about a Prelude implementation.

Dan Weston westondan at imageworks.com
Fri Jun 22 14:30:01 EDT 2007


This is how I think of it:

lazyIntMult :: Int -> Int -> Int
lazyIntMult 0 _ = 0
lazyIntMult _ 0 = 0
lazyIntMult a b = a * b

*Q> 0 * (5 `div` 0)
*** Exception: divide by zero
*Q> 0 `lazyIntMult` (5 `div` 0)
0

foldr evaluates a `f` (b `f` (c `f` ...))

Only f knows which arguments are strict and in which order to evaluate 
them. foldr knows nothing about evaluation order.

Dan

Michael T. Richter 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):
> 
>    1. 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.
>    2. 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). 
> 
> 
> Considering that I only need a single True result to make the whole 
> expression true, I'd have expected there to be some clever semantics to 
> allow exactly this.  But what I'm seeing, unless I'm really misreading 
> the code, is that if I give it a list of a million boolean expressions, 
> it will cheerfully evaluate these million boolean expressions and 
> perform a million calls to (||) before giving me a result.
> 
> Please tell me I'm wrong and that I'm missing something?
> 
> -- 
> *Michael T. Richter* <ttmrichter at gmail.com 
> <mailto:ttmrichter at gmail.com>> (*GoogleTalk:* ttmrichter at gmail.com)
> /There are two ways of constructing a software design. One way is to 
> make it so simple that there are obviously no deficiencies. And the 
> other way is to make it so complicated that there are no obvious 
> deficiencies. (Charles Hoare)/
> 
> 
> ------------------------------------------------------------------------
> 
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe




More information about the Haskell-Cafe mailing list