logoalt Hacker News

MrMcCall12/09/20241 replyview on HN

Uninitialized variables are 90% of our bugs, or so I've been told.

I don't consider a boolean "and" or "or" of a list of bools to be automatically true or false of an empty set, my friend. To me, the specific case for a boolean function applied to an empty list of bools would have to be explicitly stated in the design.

Thanks for explaining how mathematicians and logicians treat the empty set. I have more pragmatic situations to address :-)


Replies

ColinWright12/09/2024

Consider iterative code to sum a collection of ints:

  sum = 0
  for value in collection:
    sum += value
  return sum
For every non-empty collection this returns the correct result, and for the empty collection it returns 0.

Now the product:

  product = 1
  for value in collection:
    product *= value
  return product
For every non-empty collection this returns the correct result, and for the empty collection it returns 1.

Now the AND:

  A = True
  for value in collection:
    A = A AND value
  return A
For every non-empty collection this returns the correct result, and for the empty collection it returns True.

Now the OR:

  R = False
  for value in collection:
    R = R OR value
  return R
For every non-empty collection this returns the correct result, and for the empty collection it returns False.

Let's abstract it:

  Def FOLDR( initial, OP, collection )

    result = initial
    for value in collection:
      result = result OP value
    return result
So now:

  sum(     collection ) = FOLDR(   0  ,  + , collection )
  product( collection ) = FOLDR(   1  ,  * , collection )
  and(     collection ) = FOLDR( True , AND, collection )
  or(      collection ) = FOLDR( False, OR , collection )
This is why we define the results we do on empty collections. It's not just a convenience or a convention, it's consistent, and to do otherwise, even if documented, is to lay a trap for future maintainers.
show 2 replies