Do not multiply by zero

Hello,

I have a time-consuming function f :: Int -> Int and I have to do for example x * f i for numerous values of x and i. Since x can be zero, I want to avoid the evaluation of f i in these cases. Here is what I did:

times x (f i)
where 
  times x y = if x == 0 then 0 else x * y

Could you please confirm that this avoids the evaluation of f i when x = 0?

You can confirm this for yourself by replacing f with undefined and seeing what happens.

9 Likes

Btw you can probably simplify it using pattern matching. The matches are then evaluated top to bottom

times x (f i)
where 
  times 0 _ = 0
  times x y = x * y
1 Like