Logic for Programmers

原始链接: https://logicforprogrammers.com/

Python’s all function is equivalent to this: all(l) = l[0] && l[1] && l[2] ... This has a particular property: given any two lists xs and ys, we know: all(xs . ys) == all(xs) && all(ys) But that’s for any two lists, and that includes empty lists! What happens if we pick ys = []? Then xs . [] == xs, meaning: all(xs) && all([]) == all(xs . []) all(xs) && all([]) == all(xs) If all([]) = True, then this equation becomes all(xs) && True == all(xs), aka all(xs) == all(xs). If all([]) = False, then this becomes all(xs) && False == all(xs), which means all(xs) == False no matter what xs is. So it makes more sense for all(xs) = True, to preserve the property. We say that True is the identity of &&: p && True == p regardless of what p is. The same argument, incidentally, also explains why the sum of an empty list is 0 and the any of an empty list is False.

Hacker Newsnew | past | comments | ask | show | jobs | submitloginLogic for Programmers by Hillel Wayne (logicforprogrammers.com)31 points by _doctor_love 3 hours ago | hide | past | favorite | discuss help Consider applying for YC's Fall 2026 batch! Applications are open till July 27. Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact Search:
相关文章

原文

Python’s all function is equivalent to this:

all(l) = l[0] && l[1] && l[2] ...

This has a particular property: given any two lists xs and ys, we know:

all(xs . ys) == all(xs) && all(ys)

But that’s for any two lists, and that includes empty lists! What happens if we pick ys = []? Then xs . [] == xs, meaning:

all(xs) && all([]) == all(xs . [])
all(xs) && all([]) == all(xs)

If all([]) = True, then this equation becomes all(xs) && True == all(xs), aka all(xs) == all(xs). If all([]) = False, then this becomes all(xs) && False == all(xs), which means all(xs) == False no matter what xs is. So it makes more sense for all(xs) = True, to preserve the property.

We say that True is the identity of &&: p && True == p regardless of what p is. The same argument, incidentally, also explains why the sum of an empty list is 0 and the any of an empty list is False.

联系我们 contact @ memedata.com