CSC302 2011S, Class 18: Clojure (1) Overview: * Why JVM? * Clojure vs. Scheme. * A Challenge. * Lab. Admin: * Missing (unexcused): AC, DV * Missing (excused): DR * DR misses for the second time in a row, but lets me know by channelling his mind through a peer. Direct email is better, and two classes in a row is bad. * Assignment 7 will be distributed late Saturday night. * No CS table or CS extras next week. Why JVM and CLR? * "Write once, run everywhere" * Java has a huge codebase * Can leverage libraries * Can leverage *knowledge of* libraries * Can work with legacy code * JVM and CLR have lots of support * E.g., you can get JIT compiling for really fast code * Really nice GC system * Perhaps a bigger support network * JVM gives you a sandbox * Gives you leverage to get people to try your language * Supports multi-language development Detour: Implementing languages like Scheme and the wonderful hack of DrScheme * When a variable can have multiple types, the normal strategy is * Store a pointer to a struct * The struct has a "type" field * But we do a *lot* with integers. Can we save the indirection and the storage overhead? * E.g., can we build a type that is "integer or pointer" and easy to check? * "We know that words are aligned, so pointers are always multiples of four" * So, use the rightmost bit as your "Is it an integer or a pointer?" flag. * To store an integer, left shift by 1 and put a 1 in the rightmost bit. Uniform platform * Same size numbers * Little endian or big endian * Custom for order of bits and bytes in an integer Clojure Vs. Scheme * Syntax * Clojure uses def and defn instead of define * Different keywords for variables and functions * Destructuring in function definitions * Not something we teach you in Scheme; It's hard to do * (fn [param] body) rather than (lambda (param) body) * A different vector syntax * Lots of other fun chracters: Square brackets, braces, commas, etc. (1,2,3) is the same as (1 2 3) * Wildcards * true and false, * nil is false - Lisp tradition * Types (including structured types) * Map type * Keyword (:foo) * Set type * New Operations * doc * source (but only in the repl thingy) * class * filter (also in standard Scheme libraries) * Different Approaches to Operations * str - works with *anything* rather than just lists of characters * = - works with structured types, too * Other REPL - Read-Eval-Print Loop A Challenge * Write a function, (in-order? lst) that determines whether the elements of a list of numbers are in order. * Don't check preconditions. * Goal: Concision (defn in-order? [lst] (if (nil? (rest lst)) true (if (> (first lst) (first (rest lst))) false (in-order? (rest lst))))) (defn in-order? [lst] (or (nil? (rest lst)) (and (not (> (first lst) (first (rest lst))) (in-order? (rest lst)))))) (defn in-order? [lst] (reduce <= lst)) (defn in-order? [lst] (eval (cons <= lst))) (defn in_order? [lst] (apply <= lst))