Roy Smith wrote:

> If you want to take it one step further, all the boolean operators can
> be derived from nand (the dualists would insist on using nor).

Let's define the boolean values and operators using just two functions:

def true(x, y):
    return x

def false(x, y):
    return y


That's all we need to define all of Boolean algebra. Unfortunately, it's a
bit ugly in Python:

>>> true
<function true at 0xb7c3a36c>

So let's add a helper function to prettify the output:

def pr(b):
    print(b(true, false).__name__)

>>> pr(true)
true

Much nicer!


Now define NAND:

def Nand(a, b):
    return (lambda c: lambda x, y: c(y, x))(a(b, a))


and we're done. All of boolean algebra can now be derived from Nand.


>>> def Not(b):
...     return Nand(b, b)
...
>>> pr(Not(true))
false
>>> pr(Not(false))
true


>>> def And(a, b):
...     return Nand(Nand(a, b), Nand(a, b))
...
>>> pr(And(true, false))
false
>>> pr(And(true, true))
true


>>> def Or(a, b):
...     return Nand(Nand(a, a), Nand(b, b))
...
>>> pr(Or(true, false))
true
>>> pr(Or(false, false))
false


>>> def Xor(a, b):
...     return And(Nand(a, b), Or(a, b))
...
>>> pr(Xor(true, false))
true
>>> pr(Xor(true, true))
false


and so forth.



-- 
Steven

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to