Cons Python Library

0.4.7 · active · verified Sat Apr 11

The `cons` library for Python provides an implementation of Lisp/Scheme-like cons cells, aiming to emulate their semantics while integrating with Python's built-in sequence types like lists and tuples. It facilitates functional programming patterns by allowing the construction and deconstruction of pairs. The library is actively maintained, with its current version being 0.4.7, and receives updates that include dependency bumps and Python version compatibility improvements.

Warnings

Install

Imports

Quickstart

Demonstrates how to create cons cells with various Python sequence types and how to extract their `car` (head) and `cdr` (tail) components. It also shows `None` being treated as an empty list (nil) for consing.

from cons import cons, car, cdr

# Create cons cells with different sequence types
my_list_cons = cons(1, [2, 3])
my_tuple_cons = cons('a', ('b', 'c'))
my_none_cons = cons(42, None) # None acts like 'nil' in some Lisps

print(f"List cons: {my_list_cons}")
print(f"Tuple cons: {my_tuple_cons}")
print(f"None cons: {my_none_cons}")

# Accessing the head (car) and tail (cdr) of a cons cell
print(f"Car of list cons: {car(my_list_cons)}") # Output: 1
print(f"Cdr of list cons: {cdr(my_list_cons)}") # Output: [2, 3]

# cons also works with dictionaries or other iterables
from collections import OrderedDict
my_ordereddict_cons = cons(('key', 'value'), OrderedDict())
print(f"OrderedDict cons: {my_ordereddict_cons}")

view raw JSON →