import java.util.*; // // HW1 (Lisp) in Java, part 1. // These are five of the HW#1 functions - those that don't use lists-of-lists. // How much Java can we absorb? Can we tell how easy is it to use Java to // do functional programming? // // // Example Java class that is really just a set of functions. Awkward. // No instance of such a class need ever be created to use it; if an entire // class is static, it resembles a Singleton (a class with one built-in // instance). But really, you could say it is using a "class" as a package. // public class hw1 { // classic recursing on a number, as in fact(n) or fib(n) public static int foo(int n){ if (n <= 1) return 1; else return -2 * foo(n-1) * foo(n-2); } // helper functions car and cdr. Raise an exception on empty list. // Illustrate the LinkedList class in java.util private static int car(LinkedListL){ if (L.size() == 0) throw new EmptyStackException(); return L.getFirst(); } private static LinkedList cdr(LinkedListL){ if (L.size() == 0) throw new EmptyStackException(); LinkedList L2 = new LinkedList(L); L2.remove(); return L2; } public static LinkedList squares(LinkedListL){ if (L.size() == 0) return new LinkedList(); LinkedList L2 = squares(cdr(L)); L2.addFirst(car(L) * car(L)); return L2; } public static int nodds(LinkedListL){ if (L.size() == 0) return 0; return (car(L) % 2) + nodds(cdr(L)); } public static int nvowels(String s){ if (s.length() == 0) return 0; return (("aAeEiIoOuU".contains(s.substring(0,1))) ? 1:0) + nvowels(s.substring(1)); } public static String rot13(String s){ if (s.length() == 0) return ""; char c = s.charAt(0); if ("aAbBcCdDeEfFgGhHiIjJkKlLmM".contains(s.substring(0,1))) c += 13; else if ("nNoOpPqQrRsStTuUvVwWxXyYzZ".contains(s.substring(0,1))) c -= 13; return Character.toString(c) + rot13(s.substring(1)); } public static void main(String[]args){ System.out.println("foo(7)->" + foo(7)); System.out.println("nvowels(bob is one)->" + nvowels("bob is one")); System.out.println("rot13(bob is one)->" + rot13("bob is one")); System.out.println("rot13(obo vf bar)->" + rot13("obo vf bar")); LinkedList L = new LinkedList(), L2; L.add(1); L.add(2); L.add(3); L2 = squares(L); System.out.println("L has "+L2.size()+" elements"); ListIterator iterator = L2.listIterator(); while(iterator.hasNext()) { System.out.println("\t"+iterator.next()); } L.clear(); L.add(10); L.add(20); L.add(15); L.add(16); L.add(19); System.out.println("nodds(10 20 15 16 19)->" + nodds(L2)); } }