mwchase / python-structured-data

MIT License
2 stars 0 forks source link

Candidate implementation of ConsList matching utility #8

Open mwchase opened 6 years ago

mwchase commented 6 years ago

I don't know if I want this, but I sketched out some classes to implement ConsList, which would be a cons-like interface to tuple objects, for matching purposes.

Convert this to a branch/pr if I decide I want it.

import dataclasses
import typing

class ConsList:
    pass

class Nil(ConsList):
    pass

NIL = Nil()

@dataclasses.dataclass(frozen=True)
class ConsCell(ConsList):

    head: object
    next_items: typing.Tuple
    end: object

    @property
    def tail(self):
        if self.next_items:
            return ConsCell(self.next_items[0], self.next_items[1:], self.end)
        return self.end

def cons_list(*args, end=NIL):
    arglist = list(args)
    while isinstance(end, ConsCell):
        arglist.append(end.head)
        end = end.tail
    if arglist:
        return ConsCell(arglist[0], tuple(arglist[1:]), end)
    return end