hylang / hy

A dialect of Lisp that's embedded in Python
http://hylang.org
Other
5.13k stars 373 forks source link

Add `cons' support #183

Closed jd closed 10 years ago

jd commented 11 years ago

We need cons support to be called a Lisp.

Here's an idea of implementation.

  1. Build a new hy.model.cons.HyCons class that is a list of only 2 elements
  2. Add a @builds(cons) into compiler.py that create a function taking 2 arguments and returning a HyCons of these 2 arguments.
  3. Special case @builds(cons) so if you try to (cons a b) where b is an HyCons instance, you'll return an HyList([a b]). So a (cons 1 (cons 2 (cons 3 4))) builds HyList([1 2 HyCons(3, 4)]).

Alternatively, 3. may be not a special case of @builds(cons) but could be implemented on top of HyCons using __iter__, __getitem__, etc functions to emulate a list behaviour. Though that may be less optimal.

olasd commented 11 years ago

Would something along the lines of

from hy.models import HyObject
from hy.models.list import HyList

class HyCons(HyObject):
    """
    HyCons: a cons object.

    Building a HyCons of something and a HyList builds a HyList
    """

    __slots__ = ["car", "cdr"]

    def __new__(cls, car=None, cdr=None):
        if isinstance(cdr, HyList):
            return cdr.__class__([car] + cdr)

        else:
            return super(HyCons, cls).__new__(cls)

    def __init__(self, car=None, cdr=None):
        self.car = car
        self.cdr = cdr

    def __repr__(self):
        return "(%s . %s)" % (repr(self.car), repr(self.cdr))

work?

jd commented 11 years ago

:+1: except you maybe want to use car and cdr in return super(HyCons, cls).__new__(cls) no? or that doesn't matter maybe.

olasd commented 11 years ago

I'm not sure it will work, as HyObject's constructor doesn't take those arguments...

jd commented 11 years ago

Ok, so that doesn't matter then.

ghost commented 10 years ago

If you do this, be sure to consider odd corner cases like "degenerate lists" ((a . a)). Be sure you have a way to prevent them, or work with them.

Some people consider cons to be low level, and a design flaw in Lisp.

algernon commented 10 years ago

I've been using @olasd's hycons branch for adderall, it's tremendously useful. It would be very hard to implement miniKanren without it (most other miniKanren implementations on platforms without cons, emulate it)

paultag commented 10 years ago

Hurm, OK. @olasd - how are you feeling about landing this for .13? On Jan 10, 2014 9:12 AM, "Gergely Nagy" notifications@github.com wrote:

I've been using @olasd https://github.com/olasd's hycons branch for adderall, it's tremendously useful. It would be very hard to implement miniKanren without it (most other miniKanren implementations on platforms without cons, emulate it)

— Reply to this email directly or view it on GitHubhttps://github.com/hylang/hy/issues/183#issuecomment-32029867 .

theanalyst commented 10 years ago

closed via #471