Added unit tests and refactored the code for the list function

This commit is contained in:
Mike Cifelli 2017-01-06 17:10:00 -05:00
parent 5cd037fc07
commit cdb32e3777
2 changed files with 74 additions and 19 deletions

View File

@ -1,35 +1,34 @@
package function.builtin;
import function.LispFunction;
import function.*;
import sexpression.*;
/**
* <code>LIST</code> represents the LIST function in Lisp.
*/
public class LIST extends LispFunction {
/**
* Places the given S-expression into a list.
*
* @param sexpr
* the S-expression to be placed into a list
* @return
* a list with <code>sexpr</code> as the car and NIL as the cdr.
*/
private ArgumentValidator argumentValidator;
public LIST() {
this.argumentValidator = new ArgumentValidator("LIST");
}
public static Cons makeList(SExpression sexpr) {
return new Cons(sexpr, Nil.getInstance());
}
public Cons call(Cons argList) {
if (argList.nullp()) {
// return NIL if there were no arguments passed to LIST
public Cons call(Cons argumentList) {
argumentValidator.validate(argumentList);
return callRecursive(argumentList);
}
private Cons callRecursive(Cons argumentList) {
if (argumentList.nullp())
return Nil.getInstance();
}
SExpression argCar = argList.getCar();
Cons argCdr = (Cons) argList.getCdr();
SExpression firstArgument = argumentList.getCar();
Cons remainingArguments = (Cons) argumentList.getCdr();
return new Cons(argCar, call(argCdr));
return new Cons(firstArgument, callRecursive(remainingArguments));
}
}

View File

@ -0,0 +1,56 @@
package function.builtin;
import static testutil.TestUtilities.*;
import org.junit.Test;
public class LISTTester {
@Test
public void testListWithNoArguments() {
String input = "(list)";
assertSExpressionsMatch(evaluateString(input), parseString("nil"));
}
@Test
public void testListWithOneArgument() {
String input = "(list 1)";
assertSExpressionsMatch(evaluateString(input), parseString("(1)"));
}
@Test
public void testListWithTwoArguments() {
String input = "(list 2 3)";
assertSExpressionsMatch(evaluateString(input), parseString("(2 3)"));
}
@Test
public void testListWithManyArguments() {
String input = "(list 'm 'a 'n 'y 'a 'r 'g 's)";
assertSExpressionsMatch(evaluateString(input), parseString("(m a n y a r g s)"));
}
@Test
public void testListWithOneListArgument() {
String input = "(list '(1))";
assertSExpressionsMatch(evaluateString(input), parseString("((1))"));
}
@Test
public void testListWithManyListArguments() {
String input = "(list '(1) '(2 3) ())";
assertSExpressionsMatch(evaluateString(input), parseString("((1) (2 3) ())"));
}
@Test
public void testMakeList() {
assertSExpressionsMatch(LIST.makeList(parseString("22")), parseString("(22)"));
}
}