Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
 package jason.stdlib;
 
 import jason.*;

Internal action: .nth.

Description: gets the nth term of a list.

Parameters:

  • + index (integer): the position of the term, the first term is at position 0.
  • + list (list): the list where to get the term from.
  • -/+ term (term): the term at position index in the list.

Examples:

  • .nth(0,[a,b,c],X): unifies X with a.
  • .nth(2,[a,b,c],X): unifies X with c.
  • .nth(0,[a,b,c],d): false.
  • .nth(0,[a,b,c],a): true.
  • .nth(5,[a,b,c],X): error.

public class nth extends DefaultInternalAction {
    
    private static InternalAction singleton = null;
    public static InternalAction create() {
        if ( == null
             = new nth();
        return ;
    }
    @Override public int getMinArgs() { return 3; }
    @Override public int getMaxArgs() { return 3; }
    @Override protected void checkArguments(Term[] argsthrows JasonException {
        super.checkArguments(args); // check number of arguments
        if (!args[0].isNumeric()) {
            throw JasonException.createWrongArgument(this,"first argument should be numeric and not '"+args[0]+"'.");
        }
        if (!args[1].isList()) {
            throw JasonException.createWrongArgument(this,"second argument should be a list and not '"+args[1]+"'.");
        }
    }
    @Override
    public Object execute(TransitionSystem tsUnifier unTerm[] argsthrows Exception {
        checkArguments(args);
        int index = (int)((NumberTerm)args[0]).solve();
        ListTerm list = (ListTerm)args[1];
        if (index < 0 || index >= list.size()) {
            throw new JasonException("nth: index "+index+" is out of bounds ("+list.size()+")");
        }
        Term element = list.get(index);
        return un.unifies(args[2], element);
    }
New to GrepCode? Check out our FAQ X