package function.builtin.cons;

import function.*;
import sexpression.*;

@FunctionNames({ "LIST" })
public class LIST extends LispFunction {

    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 argumentList) {
        argumentValidator.validate(argumentList);

        return callRecursive(argumentList);
    }

    private Cons callRecursive(Cons argumentList) {
        if (argumentList.isNull())
            return Nil.getInstance();

        SExpression firstArgument = argumentList.getFirst();
        Cons remainingArguments = (Cons) argumentList.getRest();

        return new Cons(firstArgument, callRecursive(remainingArguments));
    }

}
