Refactored and added unit tests for listp

This commit is contained in:
Mike Cifelli 2017-01-13 12:52:05 -05:00
parent cdb32e3777
commit e543de6f12
2 changed files with 48 additions and 20 deletions

View File

@ -1,32 +1,21 @@
package function.builtin; package function.builtin;
import function.LispFunction; import function.*;
import sexpression.*; import sexpression.*;
/**
* <code>LISTP</code> represents the LISTP function in Lisp.
*/
public class LISTP extends LispFunction { public class LISTP extends LispFunction {
// The number of arguments that LISTP takes. private ArgumentValidator argumentValidator;
private static final int NUM_ARGS = 1;
public SExpression call(Cons argList) { public LISTP() {
// retrieve the number of arguments passed to LISTP this.argumentValidator = new ArgumentValidator("LISTP");
int argListLength = LENGTH.getLength(argList); this.argumentValidator.setExactNumberOfArguments(1);
// make sure we have received the proper number of arguments
if (argListLength != NUM_ARGS) {
Cons originalSExpr = new Cons(new Symbol("LISTP"), argList);
String errMsg = "too " + ((argListLength > NUM_ARGS) ? "many" : "few") + " arguments given to LISTP: "
+ originalSExpr;
throw new RuntimeException(errMsg);
} }
SExpression arg = argList.getCar(); public SExpression call(Cons argumentList) {
argumentValidator.validate(argumentList);
return (arg.listp() ? Symbol.T : Nil.getInstance()); return argumentList.getCar().listp() ? Symbol.T : Nil.getInstance();
} }
} }

View File

@ -0,0 +1,39 @@
package function.builtin;
import static testutil.TestUtilities.*;
import org.junit.Test;
import function.ArgumentValidator.*;
public class LISTPTester {
@Test
public void testListpWithList_ReturnsT() {
String input = "(listp '(1))";
assertSExpressionsMatch(evaluateString(input), parseString("T"));
}
@Test
public void testListWithNonList_ReturnsNil() {
String input = "(listp 1)";
assertSExpressionsMatch(evaluateString(input), parseString("NIL"));
}
@Test(expected = TooFewArgumentsException.class)
public void testListpWithTooFewArguments() {
String input = "(listp)";
assertSExpressionsMatch(evaluateString(input), parseString("NIL"));
}
@Test(expected = TooManyArgumentsException.class)
public void testListpWithTooManyArguments() {
String input = "(listp '() '())";
assertSExpressionsMatch(evaluateString(input), parseString("NIL"));
}
}