KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > armedbear > lisp > last


1 /*
2  * last.java
3  *
4  * Copyright (C) 2003 Peter Graves
5  * $Id: last.java,v 1.5 2003/12/13 00:58:51 piso Exp $
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, write to the Free Software
19  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20  */

21
22 package org.armedbear.lisp;
23
24 // ### last
25
// last list &optional n => tail
26
public final class last extends Primitive {
27     public last(String JavaDoc name, String JavaDoc arglist)
28     {
29         super(name,arglist);
30     }
31
32     public LispObject execute(LispObject arg) throws ConditionThrowable
33     {
34         LispObject list = checkList(arg);
35         if (list == NIL)
36             return NIL;
37         LispObject result = list;
38         int n = 1;
39         while (list instanceof Cons) {
40             list = list.cdr();
41             if (n-- <= 0)
42                 result = result.cdr();
43         }
44         return result;
45     }
46
47     public LispObject execute(LispObject first, LispObject second)
48         throws ConditionThrowable
49     {
50         LispObject list = checkList(first);
51         if (second instanceof Fixnum) {
52             int n = ((Fixnum)second).getValue();
53             if (n >= 0) {
54                 if (list == NIL)
55                     return NIL;
56                 LispObject result = list;
57                 while (list instanceof Cons) {
58                     list = list.cdr();
59                     if (n-- <= 0)
60                         result = result.cdr();
61                 }
62                 return result;
63             }
64         } else if (second instanceof Bignum) {
65             if (list == NIL)
66                 return NIL;
67             LispObject n = second;
68             LispObject result = list;
69             while (list instanceof Cons) {
70                 list = list.cdr();
71                 if (!n.plusp())
72                     result = result.cdr();
73                 n = n.decr();
74             }
75             return result;
76         }
77         return signal(new TypeError(second, "non-negative integer"));
78     }
79
80     private static final last LAST = new last("last","list &optional n");
81 }
82
Popular Tags