Unification
Project description
Straightforward Unification, extensible via dispatch.
Examples
>>> from unification import *
>>> unify(1, 1)
{}
>>> unify(1, 2)
False
>>> x = var('x')
>>> unify((1, x), (1, 2))
{~x: 2}
>>> unify((x, x), (1, 2))
False
@unifiable
class Account(object):
def __init__(self, id, name, balance):
self.id = id
self.name = name
self.balance = balance
data = [Account(1, 'Alice', 100),
Account(2, 'Bob', 0),
Account(2, 'Charlie', 0),
Account(2, 'Denis', 400),
Account(2, 'Edith', 500)]
id, name, balance = var('id'), var('name'), var('balance')
>>> [unify(Account(id, name, balance), acct) for acct in data]
[{~name: 'Alice', ~balance: 100, ~id: 1},
{~name: 'Bob', ~balance: 0, ~id: 2},
{~name: 'Charlie', ~balance: 0, ~id: 2},
{~name: 'Denis', ~balance: 400, ~id: 2},
{~name: 'Edith', ~balance: 500, ~id: 2}]
>>> [unify(Account(id, name, 0), acct) for acct in data]
[False,
{~name: 'Bob', ~id: 2},
{~name: 'Charlie', ~id: 2},
False,
False]
Function Dispatch
Unification supports function dispatch through pattern matching.
from unification.match import *
n = var('n')
@match(0)
def fib(n):
return 0
@match(1)
def fib(n):
return 1
@match(n)
def fib(n):
return fib(n - 1) + fib(n - 2)
>>> map(fib, [0, 1, 2, 3, 4, 5, 6, 7, 8, 0])
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
This patten matching can be fairly complex
name, amount = var('name'), var('amount')
@match({'status': 200, 'data': {'name': name, 'credit': amount}})
def respond(name, amount):
balance[name] += amount
@match({'status': 200, 'data': {'name': name, 'debit': amount}})
def respond(name, amount):
balance[name] -= amount
@match({'status': 404})
def respond():
print("Bad Request")
See full example in the examples directory.
History
This was carved out from the LogPy and Multiple Dispatch projects.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
unification-0.2.1.tar.gz
(6.5 kB
view details)
File details
Details for the file unification-0.2.1.tar.gz
.
File metadata
- Download URL: unification-0.2.1.tar.gz
- Upload date:
- Size: 6.5 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3089ce11f07f02ed45bc67398fec969a5956913e45128ef0e9111f4588b17f15 |
|
MD5 | ed46c07c9bdb039bb002148468e241d3 |
|
BLAKE2b-256 | 699ba4176ae231068bcb2676c2c4f7dc3c594f2e420641da0e5552db09a4a13f |