HiveBrain v1.2.0
Get Started
← Back to all entries
patterncsharpMinor

LISP-like list class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
listclasslikelisp

Problem

So, here's my code:

```
public class NList : SExp, IEnumerable
{
private Object _car;
private NList _cdr;

IEnumerator IEnumerable.GetEnumerator()
{
return new NListEnumerator(this);
}

IEnumerator IEnumerable.GetEnumerator()
{
return new NListEnumerator(this);
}

public object car ()
{
return _car;
}

public NList cdr ()
{
return _cdr;
}

public NList cons (object o)
{
return new NList(o, this);
}

public NList() // empty list
{

}

public NList(List lst)
{
if (lst.Count == 1)
{
this._car = lst[0];
this._cdr = null;
}
else
{
this._car = lst[0];
this._cdr = new NList(lst.GetRange(1, lst.Count - 1));
}
}

public NList (Object fst)
{
this._car = fst;
this._cdr = null;
}

public NList (Object fst, NList rst)
{
this._car = fst;
this._cdr = rst;
}

public object Last()
{
NList list = this;
while(list.cdr() != null)
{
list = list.cdr();
}
return list.car();
}

public int Count { get { return this.length(); } }

public int length()
{
if (this._car == null && this._cdr == null) return 0;
NList list = this;
int len = 1;
while(list.cdr() != null)
{
list = list.cdr();
len++;
}
return len;
}

public NList cddr()
{
return this.cdr().cdr();
}

public object cadr()
{
return this.cdr().car();
}

public object elm(int k)
{
if(k == 0) return car();
NList list = cdr();
for(int i = 1; i acc);
}

public static NList Reverse(NList lst)
{
NList l = lst;
NList res = null;
while(l != null)
{
res = new NList(l.car(), res)

Solution

There is a serious flaw in your handling of the empty list. A user would expect that these definitions are equivalent, but they ain't:

Nlist n1 = new NList("x");
Nlist n2 = new NList("x", new NList());


I strongly recommend to have an explicit subclass for the empty list (possibly a singleton) and to prohibit null for _cdr.

Code Snippets

Nlist n1 = new NList("x");
Nlist n2 = new NList("x", new NList());

Context

StackExchange Code Review Q#1830, answer score: 2

Revisions (0)

No revisions yet.