01: /*
02: * @(#)sort.java 1.3 05/01/14
03: *
04: * Copyright (c) 1997-2004 Sun Microsystems, Inc. All Rights Reserved.
05: *
06: * See the file "LICENSE.txt" for information on usage and redistribution
07: * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
08: */
09: package org.pnuts.lib;
10:
11: import pnuts.lang.*;
12: import java.util.*;
13:
14: public class sort extends PnutsFunction {
15:
16: public sort() {
17: super ("sort");
18: }
19:
20: public boolean defined(int nargs) {
21: return nargs == 1 || nargs == 2;
22: }
23:
24: protected Object exec(Object[] args, Context context) {
25: Comparator comp;
26: Object obj;
27: int nargs = args.length;
28: if (nargs == 1) {
29: obj = args[0];
30: comp = new PnutsComparator(context);
31: } else if (nargs == 2) {
32: obj = args[0];
33: Object c = args[1];
34: if (c instanceof PnutsFunction) {
35: comp = new FunctionComparator((PnutsFunction) c,
36: context);
37: } else if (c instanceof Comparator) {
38: comp = (Comparator) c;
39: } else {
40: throw new IllegalArgumentException(String.valueOf(c));
41: }
42: } else {
43: undefined(args, context);
44: return null;
45: }
46: if (obj instanceof List) {
47: Collections.sort((List) obj, comp);
48: } else if (obj instanceof Object[]) {
49: Arrays.sort((Object[]) obj, comp);
50: } else if (obj instanceof int[]) {
51: Arrays.sort((int[]) obj);
52: } else if (obj instanceof char[]) {
53: Arrays.sort((char[]) obj);
54: } else if (obj instanceof long[]) {
55: Arrays.sort((long[]) obj);
56: } else if (obj instanceof float[]) {
57: Arrays.sort((float[]) obj);
58: } else if (obj instanceof double[]) {
59: Arrays.sort((double[]) obj);
60: } else if (obj instanceof byte[]) {
61: Arrays.sort((byte[]) obj);
62: } else if (obj instanceof TreeSet) {
63: return obj;
64: } else if (obj instanceof Set) {
65: TreeSet ts = new TreeSet(comp);
66: ts.addAll((Set) obj);
67: return ts;
68: } else {
69: throw new IllegalArgumentException(String.valueOf(obj));
70: }
71: return obj;
72: }
73:
74: public String toString() {
75: return "function sort(elements, {func(arg) | Comparator})";
76: }
77: }
|