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