An implementation of cons in Python.
The cons package attempts to emulate the semantics of Lisp/Scheme's cons as closely as possible while incorporating all the built-in Python sequence types:
>>>fromconsimportcons, car, cdr>>>cons(1, [])
[1]
>>>cons(1, ())
(1,)
>>>cons(1, [2, 3])
[1, 2, 3]In general, cons is designed to work with collections.abc.Sequence types.
According to the cons package, None corresponds to the empty built-in list, as nil does in some Lisps:
>>>cons(1, None)
[1]The cons package follows Scheme-like semantics for empty sequences:
>>>car([])
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>ConsError: Notaconspair>>>cdr([])
Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>ConsError: NotaconspairBy default, str types are not considered cons-pairs, although they are sequences:
>>>cons("a", "string")
ConsPair('a''a string')This setting can be overridden and other types can be similarly excluded from consideration by registering classes with the abc-based classes MaybeCons and NonCons.
- Built-in support for the standard Python ordered sequence types: i.e.
list,tuple,Iterator,OrderedDict.
>>>fromcollectionsimportOrderedDict>>>cons(('a', 1), OrderedDict())
OrderedDict([('a', 1)])- Existing
consbehavior can be changed and support for new collections can be added through the generic functionscons.core._carandcons.core._cdr. - Built-in support for
unification.
>>>fromunificationimportunify, reify, var>>>unify([1, 2], cons(var('car'), var('cdr')), {})
{~car: 1, ~cdr: [2]}
>>>reify(cons(1, var('cdr')), {var('cdr'): [2, 3]})
[1, 2, 3]
>>>reify(cons(1, var('cdr')), {var('cdr'): None})
[1]pipinstallconsFirst obtain the project source:
git clone git@github.com:pythological/python-cons.gitCreate a virtual environment and install the development dependencies:
$ pip install -r requirements.txtSet up pre-commit hooks:
$ pre-commit install --install-hooks