c# top//a side-by-side reference sheet//

[#grammar-execution grammar and execution] | [#var-expr variables and expressions] | [#arithmetic-logic arithmetic and logic] | [#strings strings] | [#regexes regular expressions] | [#dates-time dates and time] | [#lists lists] | [#fixed-length-arrays fixed-length arrays] | [#dictionaries dictionaries] | [#user-defined-types user-defined types] | [#functions functions] | [#execution-control execution control] | [#exceptions exceptions] | [#streams streams] | [#emacs-buffers emacs buffers] | [#files files] | [#directories directories] | [#processes-environment processes and environment] | [#libraries-namespaces libraries and namespaces] | [#objects objects] | [#lisp-macros lisp macros] | [#reflection reflection] | [#java-interop java interop]

||~ ||~ [#common-lisp common lisp]||~ [#racket racket]||~ [#clojure clojure]||~ [#emacs-lisp emacs lisp]|| ||# version-used[#version-used-note version used] _ @< >@||##gray|//SBCL 1.2//##||##gray|//Racket 6.1//##||##gray|//Clojure 1.6//##||##gray|//Emacs 24.5//##|| ||# show-version[#show-version-note show version] _ @< >@||$ sbcl @@–@@version||$ racket @@–@@version||##gray|//displayed by repl on startup//##||$ emacs @@–@@version|| ||||||||||~ # grammar-execution[#grammar-execution-note grammar and execution]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||# compiler[#compiler-note compiler] _ @< >@|| ||$ raco make ##gray|//module//##.rkt|| ||M-x byte-compile-file|| ||# standalone-executable[#standalone-executable-note standalone executable]||(sb-ext:save-lisp-and-die _ @<  >@”##gray|//executable//##” _ @<  >@:executable t _ @<  >@:toplevel ‘##gray|//function//##)||$ mzc –exe ##gray|//executable//## ##gray|//file//##|| || || ||# interpreter[#interpreter-note interpreter] _ @<  >@||$ sbcl @@–@@script foo.lisp||$ racket -r foo.racket||##grey|//specify full path to clojure jar://## _ _ java -cp clojure.jar clojure.main foo.clj|| || ||# shebang[#shebang-note shebang]||#!/usr/bin/env sbcl @@–@@script||#!/usr/bin/env racket @@–@@script||##gray|//specify full path to clojure jar://## _ _ #!/usr/bin/env java -jar clojure.jar||#!/usr/bin/env emacs @@–@@script|| ||# repl[#repl-note repl] _ @< >@||$ sbcl||$ racket||$ java -jar /PATH/TO/clojure.jar||M-x ielm|| ||# cmd-line-program[#cmd-line-program-note command line program]|| ||$ racket -e ‘(+ 1 1)’|| || || ||# word-separator[#word-separator-note word separator] _ @< >@||##gray|//whitespace//##||##gray|//whitespace//##||##gray|//whitespace and commas//##||##gray|//whitespace//##|| ||# eol-comment[#eol-comment-note end-of-line comment]||(+ 1 1) ##gray|; adding## ||(+ 1 1) ##gray|; adding##||(+ 1 1) ##gray|; adding##||(+ 1 1) ##gray|; adding##|| ||# multiple-line-comment[#multiple-line-comment-note multiple line comment]||(+ 1 #| adding |# 1)||(+ 1 #| adding |# 1)|| || || ||||||||||~ # var-expr[#var-expr-note variables and expressions]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||# id[#id-note identifier]||##gray|//case insensitive, cannot start with digit//## _ _ ##gray|//excluded characters://## _ SP ( ) “ , ‘ @@@@ : ; # | \ _ _ ##gray|//reserved for user macros://## _ ? ! [ ] { }||##gray|//case sensitive, cannot start with digit//## _ _ ##gray|//excluded characters://## _ SP ( ) [ ] { } " , ' @@@@ ; # | ||##gray|//case sensitive, cannot start with digit//## _ _ ##gray|//permitted characters://## _ A-Z a-z 0-9 * + ! - _ ? _ _ ##gray|//these have special meaning or are reserved://## _ / . :||##gray|//case sensitive, cannot start with digit//## _ _ ##gray|//excluded characters://## _ SP ( ) “ , ‘ @@@@ ; # | \ _ [ ] || ||[# quoted-id](%23%20quoted-id.html)[#quoted-id-note quoted identifier] _ ##gray|//and escaped identifier//##||(setq |white space symbol| 3) _ _ (setq white\ space\ symbol 3)||(define |white space symbol| 3) _ _ (define white\ space\ symbol 3)||##gray|//none//## _ _ ##gray|//none//##||##gray|//none//## _ _ (setq white\ space\ symbol 3)|| ||[# local-var](%23%20local-var.html)[#local-var-note local variable]||##gray|; parallel assignment:## _ (let ((x 3) (y 4)) _ @<&nbsp;&nbsp;>@(+ x y)) _ _ ##gray|; sequential assignment:## _ (let* ((x 3) (y (* x x))) _ @<&nbsp;&nbsp;>@(+ x y))||##gray|; parallel assignment:## _ (let ((x 3) (y 4)) _ @<&nbsp;&nbsp;>@(+ x y)) _ _ ##gray|; sequential assignment:## _ (let* ((x 3) (y (* x x))) _ @<&nbsp;&nbsp;>@(+ x y))||(let [x 3 y 4] _ @<&nbsp;&nbsp;>@(+ x y)) _ _ (let [[x y] [3 4]] _ @<&nbsp;&nbsp;>@(+ x y)) _ _ (let [x 3 y (* x x)] _ @<&nbsp;&nbsp;>@(+ x y))||##gray|; parallel assignment:## _ (lexical-let ((x 3) (y 4)) _ @<&nbsp;&nbsp;>@(+ x y)) _ _ (lexical-let* ((x 3) (y (* x x))) _ @<&nbsp;&nbsp;>@(+ x y))|| ||[# global-var](%23%20global-var.html)[#global-var-note global variable] _ @<&nbsp;>@||(defparameter *x* 3) _ _ ##gray|; doesn't change x if already set:## _ (defvar *x* 3)||(define x 3) _ _ ##gray|; y is not global:## _ (define (double z) _ @<&nbsp;&nbsp;>@(define y 2) _ @<&nbsp;&nbsp;>@(* y z))||(def x 3)||(set 'x 3) _ (setq x 3)|| ||[# rm-var](%23%20rm-var.html)[#rm-var-note remove variable] _ @<&nbsp;>@||(makunbound 'x)||(namespace-undefine-variable! 'x)||(ns-unmap *ns* 'x)||(makunbound 'x)|| ||[# null](%23%20null.html)[#null-note null] _ @<&nbsp;>@||nil '()||null '()||##gray|; same value as null in Java:## _ nil||nil '()|| ||[# null-test](%23%20null-test.html)[#null-test-note null test] _ @<&nbsp;>@||(null x)||(null? x)||(nil? x)||(null x)|| ||[# id-as-val](%23%20id-as-val.html)[#id-as-val-note identifier as value]||'x _ (quote x)||'x _ (quote x)||'x _ (quote x)||'x _ (quote x)|| ||[# id-test](%23%20id-test.html)[#id-test-note identifier test] _ @<&nbsp;>@||(symbolp 'x)||(symbol? 'x)||(symbol? 'x)||(symbolp 'x)|| ||identifier equality test||(eq 'x 'x)||(eq? 'x 'x)||(= 'x 'x)||(eq 'x 'x)|| ||[# non-referential-id](%23%20non-referential-id.html)[#non-referential-id-note non-referential identifier] _ @<&nbsp;>@||:foo||#:foo||:foo||:foo|| ||[# id-attr](%23%20id-attr.html)[#id-attr-note identifier attributes] _ ##gray|//set, get, remove//##||(set 'x 13) _ _ (setf (get 'x :desc) "unlucky") _ (get 'x :desc) _ (remprop 'x :desc)||##gray|//none//##||##gray|; value must be instance of clojure.lang.IObj:## _ _ (def x (with-meta [13] {:desc "unlucky"})) _ (get (meta x) :desc) _ ##gray|; none##||(set 'x 13) _ _ (setf (get 'x :desc) "unlucky") _ (get 'x :desc) _ (remprop 'x :desc)|| ||||||||||~ [# arithmetic-logic](%23%20arithmetic-logic.html)[#arithmetic-logic-note arithmetic and logic]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[# true-false](%23%20true-false.html)[#true-false-note true and false]||t nil||#t #f _ true false||true false||t nil|| ||[# falsehoods](%23%20falsehoods.html)[#falsehoods-note falsehoods] _ @<&nbsp;>@||nil ()||#f false||false nil||nil ()|| ||[# logical-op](%23%20logical-op.html)[#logical-op-note logical operators] _ @<&nbsp;>@||(or (not t) (and t nil))||(or (not #t) (and #t #f))||(or (not true) (and true false))||(or (not t) (and t nil))|| ||[# relational-op](%23%20relational-op.html)[#relational-op-note relational operators] _ @<&nbsp;>@||@@=@@ /= < > <= >=||@@=@@ ##gray|//none//## < > <= >=||@@=@@ not= < > <= >=||@@=@@ /= < > <= >=|| ||[# min-max](%23%20min-max.html)[#min-max-note min and max]||(min 1 2 3) _ (max 1 2 3)||(min 1 2 3) _ (max 1 2 3)||(min 1 2 3) _ (max 1 2 3)||(min 1 2 3) _ (max 1 2 3)|| ||[# num-predicates](%23%20num-predicates.html)[#num-predicates-note numeric predicates]||numberp integerp _ rationalp floatp _ realp complexp||number? integer? _ rational? inexact? _ real? complex?||number? integer? _ rational? float? _ ##gray|//none//## ##gray|//none//##||numberp integerp _ ##gray|//none//## floatp _ ##gray|//none//## ##gray|//none//##|| ||[# arith-op](%23%20arith-op.html)[#arith-op-note arithmetic operators] _ @<&nbsp;>@||+ - * / mod||+ - * / modulo||+ - * / mod||+ - * / %|| ||[# int-div](%23%20int-div.html)[#int-div-note integer division] _ ##gray|//and remainder//##||(truncate 7 3) _ (rem 7 3)||(quotient 7 3) _ (remainder 7 3)||(quot 7 3) _ (rem 7 3)||(/ 7 3) _ (% 7 3)|| ||[# int-div-zero](%23%20int-div-zero.html)[#int-div-zero-note integer division by zero]||##gray|division-by-zero //error//##||##gray|division by zero //error//##|| ||##gray|arith-error##|| ||[# float-div](%23%20float-div.html)[#float-div-note float division]||##gray|//rational://## _ (/ 7 3) _ _ ##gray|//float://## _ (/ 7 (* 3 1.0))||##gray|//rational://## _ (/ 7 3) _ _ ##gray|//float://## _ (/ 7 (float 3))||##gray|//rational://## _ (/ 7 3) _ _ ##gray|//float://## _ (/ 7 (* 3 1.0))||##gray|//integer quotient://## _ (/ 7 3) _ _ ##gray|//float://## _ (/ 7 (* 3 1.0))|| ||[# float-div-zero](%23%20float-div-zero.html)[#float-div-zero-note float division by zero]||##gray|division-by-zero //error//##|| || ||-1.0e+INF, -0.0e+NaN, ##gray|//or//## 1.0e+INF|| ||[# power](%23%20power.html)[#power-note power]||(expt 2 32)||(expt 2 32)||##gray|//returns float://## _ (Math/pow 2 32)||(expt 2 32)|| ||[# sqrt](%23%20sqrt.html)[#sqrt-note sqrt] _ @<&nbsp;>@||(sqrt 2)||(sqrt 2)||(Math/sqrt 2)||(sqrt 2)|| ||[# sqrt-negative-one](%23%20sqrt-negative-one.html)[#sqrt-negative-one sqrt -1] _ @<&nbsp;>@||#c(0.0 1.0)||0+1i|| ##gray|//(Math/sqrt -1)://## NaN||-0.0e+NaN|| ||[# transcendental-func](%23%20transcendental-func.html)[#transcendental-func-note transcendental functions]||exp log sin cos tan asin acos atan atan||exp log sin cos tan asin acos atan atan||Math/exp Math/log Math/sin Math/cos Math/tan Math/asin Math/acos Math/atan Math/atan2||exp log sin cos tan asin acos atan atan|| ||[# float-truncation](%23%20float-truncation.html)[#float-truncation-note float truncation]||##gray|//return two values, first is integer://## _ truncate round ceiling floor||##gray|//return floats://## _ truncate round ceiling floor||##gray|//return integers://## _ int Math/round _ ##gray|//return floats://## _ Math/ceil Math/floor||truncate round ceiling floor _ fround fceiling ffloor _ ##gray|truncate //returns integer//##|| ||[# abs-val](%23%20abs-val.html)[#abs-val-note absolute value] _ ##gray|//and signum//##||abs signum||abs _ ##gray|//racket://## sgn||Math/abs Math/signum||abs signum|| ||[# int-overflow](%23%20int-overflow.html)[#int-overflow-note integer overflow] _ @<&nbsp;>@||##gray|//none; arbitrary-precision integers//##||##gray|//none; arbitrary-precision integers//##||##gray|clojure.lang.Numbers.throwIntOverflow //exception//##|| || ||[# float-overflow](%23%20float-overflow.html)[#float-overflow-note float overflow] _ @<&nbsp;>@||##gray|floating-point-overflow //error//##|| ||##gray|//not literals://## _ -Infity NaN Infinity|| || ||[# rational-construction](%23%20rational-construction.html)[#rational-construction-note rational construction]||(/ 3 7) _ _ ##gray|; literal:## _ 3/7||(/ 3 7) _ _ ##gray|; literal:## _ 3/7 _ _ ##gray|; also rational:## _ 2.718 _ (exp 1)||(/ 3 7) _ _ ##gray|; literal:## _ 3/7|| || ||[# rational-decomposition](%23%20rational-decomposition.html)[#rational-decomposition-note rational decomposition]||(numerator 3/7) _ (denominator 3/7)||(numerator 3/7) _ (denominator 3/7)||(numerator 3/7) _ (denominator 3/7)||##gray|//none//## ##gray|//none//##|| ||[# complex-construction](%23%20complex-construction.html)[#complex-construction-note complex construction]||#c(1 2)||1+2i _ (+ 1 +2i)||##gray|//none//##||##gray|//none//##|| ||[# complex-decomposition](%23%20complex-decomposition.html)[#complex-decomposition-note complex decomposition]||(realpart #c(1 2)) _ (imagpart #c(1 2)) _ (phase #c(1 2)) _ (abs #c(1 2)) _ (conjugate #c(1 2))||(real-part 1+2i) _ (imag-part 1+2i) _ (angle 1+2i) _ (magnitude 1+2i) _ (conjugate 1+2i)||##gray|//none//## _ ##gray|//none//##||##gray|//none//## ##gray|//none//##|| ||[# random-num](%23%20random-num.html)[#random-num-note random number] _ ##gray|//uniform integer, uniform float, normal float//##||(random 100) _ (random 1.0) _ ##gray|//none//##||(random 100) _ (random) _ ##gray|//none//##||(def rnd (java.util.Random.)) _ (.nextInt rnd 100) _ (.nextFloat rnd) _ (.nextGaussian rnd)||(random 100) _ ##gray|//none//## _ ##gray|//none//##|| ||[# random-seed](%23%20random-seed.html)[#random-seed-note random seed]||(setq *random-state* _ @<&nbsp;&nbsp;>@(sb-ext:seed-random-state 17))||(random-seed 17)|| || || ||[# bit-op](%23%20bit-op.html)[#bit-op-note bit operators]||ash ##gray|//left shift when 2nd argument positive//## logand logior logxor lognot||arithmetic-shift ##gray|//left shift when 2nd argument positive//## bitwise-and bitwise-ior bitwise-xor bitwise-not||bit-shift-left bit-shift-right bit-and bit-or bit-xor bit-not||lsh ##gray|//left shift when 2nd argument positive//## logand logior logxor lognot|| ||[# binary-octal-hex-literals](%23%20binary-octal-hex-literals.html)[#binary-octal-hex-literals-note binary, octal, and hex literals]||#b101010 _ #o52 _ #x2a||#b101010 _ #o52 _ #x2a|| || || ||[# radix](%23%20radix.html)[#radix-note radix] _ @<&nbsp;>@||(format nil "~7r" 42)|| || || || ||||||||||~ [# strings](%23%20strings.html)[#strings-note strings]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[# str-test](%23%20str-test.html)[#str-test-note string test] _ @<&nbsp;>@||(stringp "foo")||(string? "foo")||(string? "foo")||(stringp "foo")|| ||[# str-literal](%23%20str-literal.html)[#str-litera-notel string literal] _ @<&nbsp;>@||"foo bar"||"foo bar"||"foo bar"||"foo bar"|| ||[# newline-in-str-literal](%23%20newline-in-str-literal.html)[#newline-in-str-literal-note newline in literal] _ @<&nbsp;>@||##gray|//yes//##||##gray|//yes//##||##gray|//yes//##||##gray|//yes//##|| ||[# str-literal-esc](%23%20str-literal-esc.html)[#str-literal-esc-note literal escapes]||\" \\||\t \n \r \" \\ \##gray|//ooo//## \u##gray|//hhhh//##||\b \t \n \f \r \" \\ \##gray|//ooo//## \u##gray|//hhhh//##||\b \t \n \f \r \" \\ \##gray|//ooo//## \u##gray|//hhhh//## \x##gray|//h//## - \x##gray|//hhhhhh//## \C-##gray|//x//## \M-##gray|//x//##|| ||[# str-ctor](%23%20str-ctor.html)[#str-ctor-note constructor] _ @<&nbsp;>@|| ||(string #\f #\o #\o)|| ||(string ?f ?o ?o)|| ||[# fmt-str](%23%20fmt-str.html)[#fmt-str-note format string]||(format nil "~a: ~a ~,2f" "Foo" 7 13.457)||(format "~a ~a ~a" "Foo" 7 13.457)||(String/format "%s: %d %.2f" _ @<&nbsp;&nbsp;>@(to-array ["Foo" 7 13.457]))|| (format "%s: %d %.2f" "Foo" 7 13.457)|| ||[# fmt-specifiers](%23%20fmt-specifiers.html)[#fmt-specifiers-note format specifiers]||##gray|~a@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@any type, human readable _ ~s@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@any time, read parseable _ ~%@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@newline _ ~~@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@tilde _ ~c@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@character _ ~,5f@<&nbsp;&nbsp;>@5 digits right of decimal mark _ ~d@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@decimal _ ~x@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@hex _ ~o@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@octal _ ~b@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@binary##||##gray|~a@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@any type, human readable _ ~s@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@any time, read parseable _ ~%@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@newline _ ~~@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@tilde _ ~c@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@character _ _ ~d@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@decimal _ ~x@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@hex _ ~o@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@octal _ ~b@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@binary##|| || || ||[# compare-str](%23%20compare-str.html)[#compare-str-note compare strings]||(string= "foo" "bar") _ (string< "foo" "bar")||(string=? "foo" "bar") _ (string<? "foo" "bar")||(.equals "foo" "bar") _ (.compareTo "foo" "bar")||(string= "foo" "bar") _ (string< "foo" "bar")|| ||[# str-concat](%23%20str-concat.html)[#str-concat-note concatenate] _ @<&nbsp;>@||(concatenate 'string "foo " "bar " "bar")||(string-append "foo " "bar " "baz")||(str "foo " "bar " "baz")||(concat "foo " "bar " "baz")|| ||[# str-replicate](%23%20str-replicate.html)[#str-replicate-note replicate]||make-string 3 :initial-element #\f)||(make-string 3 #\f)||(String. (into-array _ @<&nbsp;&nbsp;>@(. Character TYPE) _ @<&nbsp;&nbsp;>@(repeat 3 \f)))||(make-string 3 ?f)|| ||[# translate-case](%23%20translate-case.html)[#translate-case-note translate case]||(string-downcase "FOO") _ (string-upcase "foo")||(string-downcase "FOO") _ (string-upcase "foo")||(.toLowerCase "FOO")||(downcase "FOO") _ (upcase "foo")|| ||[# capitalize](%23%20capitalize.html)[#capitalize-note capitalize]||##gray|; "Foo Bar":## _ (string-capitalize "foo bar")|| || ||##gray|; "Foo Bar":## _ (capitalize "foo")|| ||[#string-trim trim]||(string-trim _ @<&nbsp;&nbsp;>@'(#\space #\tab #\newline) _ @<&nbsp;&nbsp;>@" foo ")|| (require srfi/13/string) _ (string-trim-both " foo ")||(.trim " foo ")||##gray|//none; see notes for an implementation//##|| ||[# pad](%23%20pad.html)[#pad-note pad] _ ##gray|//on right, on left//##||(format nil "~10a" "foo") _ (format nil "~10@a" "foo")|| || || || ||[# num-to-str](%23%20num-to-str.html)[#num-to-str-note number to string]||(concatenate 'string _ @<&nbsp;&nbsp;>@"value: " _ @<&nbsp;&nbsp;>@(princ-to-string 8))||(string-append _ @<&nbsp;&nbsp;>@"value: " _ @<&nbsp;&nbsp;>@(number->string 8))||(str "Value: " 8)||(concat _ @<&nbsp;&nbsp;>@"value: " _ @<&nbsp;&nbsp;>@(number-to-string 8))|| ||[# str-to-num](%23%20str-to-num.html)[#str-to-num-note string to number]|| (+ 7 (parse-integer "12")) _ @<&nbsp;>@ _ (+ 73.9 (read-from-string ".037"))||(+ 7 (string->number "12")) _ @<&nbsp;>@ _ (+ 73.9 (string->number ".037"))||(+ 7 (Integer/parseInt "12")) _ @<&nbsp;>@ _ (+ 73.9 (Float/parseFloat ".037"))||(+ 7 (string-to-number "12")) _ @<&nbsp;>@ _ (+ 73.9 (string-to-number ".037"))|| ||[# split](%23%20split.html)[#split-note split]||(cl-ppcre:split _ @<&nbsp;&nbsp;>@"[ \t\n]+" _ @<&nbsp;&nbsp;>@"foo bar baz")||(regexp-split #rx"[ \n\t]+" _ @<&nbsp;&nbsp;>@"foo bar baz")||(seq _ @<&nbsp;&nbsp;>@(.split "foo bar baz" _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@"[ \t\n]+"))||(split-string "foo bar baz")|| ||[# str-join](%23%20str-join.html)[#str-join-note string join]||(reduce _ @<&nbsp;&nbsp;>@(lambda (m o) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(concatenate 'string m " " o)) _ @<&nbsp;&nbsp;>@'("foo" "bar" "baz"))||(string-join _ @<&nbsp;&nbsp;>@'("foo" "bar" "baz") _ @<&nbsp;&nbsp;>@" ")||(reduce #(str %1 " " %2) _ @<&nbsp;&nbsp;>@'("foo" "bar" "baz"))||(reduce _ @<&nbsp;&nbsp;>@(lambda (m o) (concat m " " o)) _ @<&nbsp;&nbsp;>@'("foo" "bar" "baz"))|| ||[# str-len](%23%20str-len.html)[#str-len-note length] _ @<&nbsp;>@||(length "foo")||(string-length "foo")||(.length "foo")||(length "foo")|| ||[# index-substr](%23%20index-substr.html)[#index-substr-note index of substring]||(search "bar" "foo bar")||##gray|//racket://## _ (require srfi/13/string) _ (string-contains "foo bar" "bar")||(.indexOf "foo bar" "bar")||(search "bar" "foo bar")|| ||[# extract-substr](%23%20extract-substr.html)[#extract-substr-note extract substring] _ @<&nbsp;>@||(subseq "foo bar" 4 7)||(substring "foo bar" 4 7)||(.substring "foo bar" 4 7)||(substring "foo bar" 4 7)|| ||[# char-literal](%23%20char-literal.html)[#char-literal-note character literal]||#\a #\space #\newline #\backspace #\tab #\linefeed #\page #\return #\rubout||#\a #\space #\newline #\backspace #\tab #\linefeed #\page #\return #\nul #\vtab #\alarm #\esc #\delete _ ##gray|//not in racket:// #\alarm #\esc #\delete##||\a \newline \space \backspace \tab ##gray|//?//## \formfeed \return ##gray|//?//##||?a ?\b ?\t ?\n ?\f ?\r ?\" ?\\ ?\##gray|//ooo//## ?\u##gray|//hhhh//## ?\x##gray|//h//## - ?\x##gray|//hhhhhh//## ?\C-##gray|//x//## ?\M-##gray|//x//##|| ||[# char-test](%23%20char-test.html)[#char-test-note test characters] _ @<&nbsp;>@||(characterp #\x) _ (alpha-char-p #\x) _ (alphanumericp #\x) _ (digit-char-p #\7) _ (lower-case-p #\x) _ (upper-case-p #\X)||(char? #\x)||(char? \x)||(characterp ?x)|| ||[# chr-ord](%23%20chr-ord.html)[#chr-ord-note chr and ord]||(code-char 97) _ (char-code #\a)||(integer->char 97) _ (char->integer #\a)||(char 97) _ (int \a)|| || ||[# str-to-char-array](%23%20str-to-char-array.html)[#str-to-char-array-note to array of characters]|| ||##gray|; list: ## _ (string->list "foo")|| || || ||[# lookup-char](%23%20lookup-char.html)[#lookup-char-note character lookup] _ @<&nbsp;>@||(char "foo" 0)||(string-ref "foo" 0)||(.charAt "foo" 0)||(aref "foo" 0)|| ||||||||||~ [# regexes](%23%20regexes.html)[#regexes-note regular expressions]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[# regex-literal](%23%20regex-literal.html)[#regex-literal-note literal]||##gray|//use a string://## _ "\\b\\d{5}\\b"||##gray|//posix extended://## _ #rx"^[0-9][0-9][0-9][0-9][0-9]$" _ (regexp "^[0-9][0-9][0-9][0-9][0-9]$") _ _ ##gray|//perl style://## _ #px"\\b\\d{5}\\b" _ (pregexp "\\b\\d{5}\\b")||#"\b\d{5}\b"|| || ||[# char-class-abbrev](%23%20char-class-abbrev.html)[#char-class-abbrev-note character class abbrevations]||. \d \D \s \S \w \W||##gray|//regexp://## _ . _ _ ##gray|//pregexp://## _ . \d \D \s \S \w \W||. \d \D \s \S \w \W||. \w \W \ca \cl \cg \Ca \Cl \Cg \s##gray|//x//## _ _ ##gray|\ca \cl //and// \cg //match ASCII, Latin, and Greek characters.//## _ _ ##gray|//Character classes of the form// \sx //depend on the current syntax table.//##|| ||[# regex-anchors](%23%20regex-anchors.html)[#regex-anchors-note anchors]||^ $ \b \B||##gray|//regexp://## _ ^ $ _ _ ##gray|//pregexp://## _ ^ $ \b \B||^ $ \A \b \B \G \z \Z||^ $ \b \B|| ||[# regex-test](%23%20regex-test.html)[#regex-test-note match test]||(ql:quickload "cl-ppcre") _ _ (if (cl-ppcre:all-matches "1999" s) _ @<&nbsp;&nbsp;>@(format t "party!"))||(regexp-match #rx"bar" "foo bar")||(re-find #"bar" "foo bar")||(string-match "bar" "foo bar")|| ||[# case-insensitive-regex](%23%20case-insensitive-regex.html)[#case-insensitive-regex-note case insensitive match test]|| ||(regexp-match #px"(?i:lorem)" "Lorem")||(re-find #"(?i:lorem)" "Lorem")|| || ||[# subst](%23%20subst.html)[#subst-note substitution]||(cl-ppcre:regex-replace "[^l]l" _ @<&nbsp;&nbsp;>@"hello" _ @<&nbsp;&nbsp;>@"EL") _ @<&nbsp;>@ _ (cl-ppcre:regex-replace-all "[^l]l" _ @<&nbsp;&nbsp;>@"hello hello" _ @<&nbsp;&nbsp;>@"EL")||(regexp-replace #rx"el" _ @<&nbsp;&nbsp;>@"hello" _ @<&nbsp;&nbsp;>@"EL") _ @<&nbsp;>@ _ (regexp-replace* #rx"el" _ @<&nbsp;&nbsp;>@"hello hello" _ @<&nbsp;&nbsp;>@"EL")||(.replaceFirst "hello" "[^l]l" "XX") _ @<&nbsp;>@ _ (.replaceAll "hello hello" _ @<&nbsp;&nbsp;>@"[^l]l" "XX")||##gray|//?//## _ @<&nbsp;>@ _ (replace-regexp-in-string "[^l]l" _ @<&nbsp;&nbsp;>@"EL" _ @<&nbsp;&nbsp;>@"hello hello")|| ||[# group-capture](%23%20group-capture.html)[#group-capture-note group capture]|| ||(match (regexp-match _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@#px"(\\d{4})-(\\d{2})-(\\d{2})" _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@"2010-06-03") _ @<&nbsp;&nbsp;>@[(list s yr mn dy) (list yr mn dy)])|| (let [[_ yr mn dy] _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(re-find #"(\d{4})-(\d{2})-(\d{2})" _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@"2010-06-03")] _ @<&nbsp;&nbsp;>@yr)|| || ||[# scan](%23%20scan.html)[#scan-note scan]|| || ||(re-seq #"\w+" "dolor sit amet")|| || ||[# backreference](%23%20backreference.html)[#backreference-note backreference in match and substitution]|| ||(regexp-match #px"(\\w+) \\1" "do do") _ _ (regexp-replace #px"(\\w+) (\\w+)" _ @<&nbsp;&nbsp;>@"do re" _ @<&nbsp;&nbsp;>@"\\2 \\1")|| || || ||||||||||~ [# dates-time](%23%20dates-time.html)[#dates-time-note dates and time]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[# broken-down-datetime-type](%23%20broken-down-datetime-type.html)[#broken-down-datetime-type-note broken-down datetime type]||##gray|//No dedicated type; a list of 9 values is used:// _ _ @<&nbsp;&nbsp;>@second: 0-59 _ @<&nbsp;&nbsp;>@minute: 0-59 _ @<&nbsp;&nbsp;>@hour: 0-23 _ @<&nbsp;&nbsp;>@day of month: 1-31 _ @<&nbsp;&nbsp;>@month: 1-12 _ @<&nbsp;&nbsp;>@year: 4 digits _ @<&nbsp;&nbsp;>@day of week: 0-6 for Mon-Sun _ @<&nbsp;&nbsp;>@is daylight savings time: t or nil _ @<&nbsp;&nbsp;>@timezone: negated UTC offset in hours|| || || || ||[# current-datetime](%23%20current-datetime.html)[#current-datetime-note current datetime]||(get-decoded-time)||(require racket/date) _ _ (current-date)||(def dt (new java.util.Date))||(current-time)|| ||[# current-unix-epoch](%23%20current-unix-epoch.html)[#current-unix-epoch-note current unix epoch]||##gray|; seconds since Jan 1, 1900:## _ (get-universal-time)||(current-seconds)||(/ (System/currentTimeMillis) 1000.0)||(float-time)|| ||[# unix-epoch-to-broken-down-datetime](%23%20unix-epoch-to-broken-down-datetime.html)[#unix-epoch-to-broken-down-datetime-note unix epoch to broken-down datetime]||(decode-universal-time _ @<&nbsp;&nbsp;>@(get-unversal-time))||(seconds->date (current-seconds))||(def dt (new java.util.Date _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(System/currentTimeMillis)))||(seconds-to-time (float-time))|| ||[# broken-down-datetime-to-unix-epoch](%23%20broken-down-datetime-to-unix-epoch.html)[#broken-down-datetime-to-unix-epoch-note broken-down datetime to unix epoch]||(encode-universal-time 0 22 10 31 5 2015)||(require racket/date) _ _ (date->seconds (current-date))||(/ (.getTime (new java.util.Date)) 1000.0)||(multiple-value-bind (b s) _ @<&nbsp;&nbsp;>@(current-time) _ @<&nbsp;&nbsp;>@(+ (* b (expt 2 16)) s))|| ||[# fmt-datetime](%23%20fmt-datetime.html)[#fmt-datetime-note format datetime]|| || ||(def s "yyyy-MM-dd HH:mm:ss") _ (def fmt (new java.text.SimpleDateFormat s)) _ _ (.format fmt (new java.util.Date))||(format-time-string _ @<&nbsp;&nbsp;>@"%Y-%m-%d %H:%M:%S" _ @<&nbsp;&nbsp;>@(current-time))|| ||[# parse-datetime](%23%20parse-datetime.html)[#parse-datetime-note parse datetime]|| ||(require (prefix-in s19. srfi/19)) _ _ (define (date-str->unix-time s fmt) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(s19.time-second _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(s19.date->time-utc _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(s19.string->date s fmt)))) _ _ (date-str->unix-time _ @<&nbsp;&nbsp;>@"2015-05-31 07:06:00" _ @<&nbsp;&nbsp;>@"~Y-~m-~d ~H:~M:~S")||(def s "yyyy-MM-dd HH:mm:ss") _ (def fmt (new java.text.SimpleDateFormat s)) _ _ (.parse fmt "2015-05-30 09:14:14")|| || ||[# datet-parts](%23%20datet-parts.html)[#date-parts-note date parts]||(multiple-value-bind _ @<&nbsp;&nbsp;>@(ss mi hr dy mo yr) _ @<&nbsp;&nbsp;>@(get-decoded-time) _ @<&nbsp;&nbsp;>@(list ss mi hr) ##gray|; quiesce warning## _ @<&nbsp;&nbsp;>@(list dy mo yr))||(date-year (current-date)) _ (date-month (current-date)) _ (date-day (current-date))||(def cal (new java.util.GregorianCalendar)) _ (.setTime cal dt) _ _ (.get cal java.util.Calendar/DAY_OF_MONTH) _ (+ (.get cal java.util.Calendar/MONTH) 1) _ (.get cal java.util.Calendar/YEAR)||(multiple-value-bind _ @<&nbsp;&nbsp;>@(ss mi hr dy mo yr) _ @<&nbsp;&nbsp;>@ (decode-time (current-time)) _ @<&nbsp;&nbsp;>@(list dy mo yr))|| ||[# time-parts](%23%20time-parts.html)[#time-parts-note time parts]||(multiple-value-bind _ @<&nbsp;&nbsp;>@(ss mi hr) _ @<&nbsp;&nbsp;>@(get-decoded-time) _ @<&nbsp;&nbsp;>@(list ss mi hr))||(date-hour (current-date)) _ (date-minute (current-date)) _ (date-second (current-date))||(def cal (new java.util.GregorianCalendar)) _ (.setTime cal dt) _ _ (.get cal java.util.Calendar/HOUR_OF_DAY) _ (.get cal java.util.Calendar/MINUTE) _ (.get cal java.util.Calendar/SECOND)||(multiple-value-bind _ @<&nbsp;&nbsp;>@(ss mi hr dy mo yr) _ @<&nbsp;&nbsp;>@ (decode-time (current-time)) _ @<&nbsp;&nbsp;>@(list ss mi hr))|| ||[# build-datetime](%23%20build-datetime.html)[#build-datetime-note build broken-down datetime]||(encode-universal-time 0 22 10 31 5 2015)|| ||(let _ @<&nbsp;&nbsp;>@[yr 2015 mo 5 dy 31 hr 10 mi 22 ss 0] _ @<&nbsp;&nbsp;>@(def cal _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(new java.util.GregorianCalendar _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@yr (- mo 1) dy hr mi ss)))||(encode-time 0 50 8 31 5 2015)|| ||||||||||~ [# lists](%23%20lists.html)[#lists-note lists]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[#list-literal literal] _ @<&nbsp;>@||'(1 2 3) _ (quote (1 2 3))||'(1 2 3) _ '[1 2 3] _ '{1 2 3} _ (quote (1 2 3))||'(1 2 3) _ (quote (1 2 3))||'(1 2 3) _ (quote (1 2 3))|| ||constructor _ @<&nbsp;>@||(list 1 2 3)||(list 1 2 3)||(list 1 2 3)||(list 1 2 3)|| ||predicate _ @<&nbsp;>@||(listp '(1 2 3))||(list? '(1 2 3))||(list? '(1 2 3))||(listp '(1 2 3))|| ||empty test||##gray|nil //and// '() //are synonyms and evaluate as false in a boolean context. All other values are true.//##||(empty? '())||(empty? ())||##gray|nil //and// '() //are synonyms and evaluate as false in a boolean context. All other values are true.//##|| ||evaluating the empty list||nil||##gray|//error//##||()||nil|| ||[#cons cons] _ @<&nbsp;>@||(cons 1 '(2 3))||(cons 1 '(2 3))||(cons 1 '(2 3))||(cons 1 '(2 3))|| ||head _ @<&nbsp;>@||(car '(1 2 3)) _ (first '(1 2 3))||(car '(1 2 3)) _ (first '(1 2 3))||first||car|| ||tail _ @<&nbsp;>@||(cdr '(1 2 3)) _ (rest '(1 2 3))||(cdr '(1 2 3)) _ (rest '(1 2 3))||(rest '(1 2 3)) _ (next '(1 2 3))||(cdr '(1 2 3)) _ (rest '(1 2 3))|| ||head and tail of empty list||##gray|//both evaluate to// nil##||##gray|//error//##||()||##gray|//both evaluate to// nil##|| ||length _ @<&nbsp;>@||(length '(1 2 3))||(length '(1 2 3))||(count '(1 2 3))||(length '(1 2 3))|| ||equality test _ @<&nbsp;>@||(equal '(1 2 3) '(1 2 3))||(equal? '(1 2 3) '(1 2 3))||(= '(1 2 3) '(1 2 3))||(equal '(1 2 3) '(1 2 3))|| ||nth element||##gray|; indexed from zero:## _ (nth 2 '(1 2 3 4))||(list-ref '(1 2 3 4) 2)||(nth '(1 2 3 4) 2)||(nth 2 '(1 2 3 4))|| ||out-of-bounds behavior||nil||##gray|//error//##||##gray|//raises// IndexOutOfBoundsException##||nil|| ||element index||(position 7 '(5 6 7 8))||(require srfi/1) _ _ (list-index (lambda (x) (= x 7)) '(5 6 7 8))||##gray|//none//##||(position 7 '(5 6 7 8))|| ||concatenate _ @<&nbsp;>@||(append '(1 2 3) '(4 5 6))||(append '(1 2 3) '(4 5 6))||(concat '(1 2 3) '(4 5 6))||(append '(1 2 3) '(4 5 6))|| ||[#take take] _ @<&nbsp;>@||##gray|//none//##||(take '(1 2 3 4) 2)||(take 2 '(1 2 3 4))||(subseq '(1 2 3 4) 0 2)|| ||[#drop drop] _ @<&nbsp;>@||(nthcdr 2 '(1 2 3 4))||(drop '(1 2 3 4) 2)||(drop 2 '(1 2 3 4))||(nthcdr 2 '(1 2 3 4))|| ||last element _ @<&nbsp;>@||(car (last '(1 2 3)))||(last '(1 2 3))||(last '(1 2 3))||(car (last '(1 2 3)))|| ||all but last element||(butlast '(1 2 3))||(define a '(1 2 3)) _ (take a (- (length a) 1))||(butlast '(1 2 3))||(butlast '(1 2 3))|| ||reverse _ @<&nbsp;>@||(reverse '(1 2 3))||(reverse '(1 2 3))||(reverse '(1 2 3))||(reverse '(1 2 3))|| ||[#sort sort] _ @<&nbsp;>@||(sort '(3 2 4 1) '<)||(sort '(3 2 4 1) <)||(sort < '(3 2 4 1))||(sort '(3 2 4 1) '<)|| ||dedupe _ @<&nbsp;>@||(remove-duplicates '(1 1 2 3))||(remove-duplicates '(1 1 2 3))|| ||(remove-duplicates '(1 1 2 3))|| ||membership _ @<&nbsp;>@||(member 7 '(1 2 3))||(member 7 '(1 2 3))|| ||(member 7 '(1 2 3)|| ||[#map map]||(mapcar _ @<&nbsp;&nbsp;>@(lambda (x) (* x x)) _ @<&nbsp;&nbsp;>@'(1 2 3))||(map (lambda (x) (* x x)) '(1 2 3))||(map #(* % %) '(1 2 3))||(mapcar _ @<&nbsp;&nbsp;>@(lambda (x) (* x x)) _ @<&nbsp;&nbsp;>@'(1 2 3))|| ||[#filter filter]||(remove-if-not _ @<&nbsp;&nbsp;>@(lambda (x) (> x 2)) _ @<&nbsp;&nbsp;>@'(1 2 3)) _ _ ##gray|; remove-if returns complement##||(filter _ @<&nbsp;&nbsp;>@(lambda (x) (> x 2)) _ @<&nbsp;&nbsp;>@'(1 2 3)) _ _ ##gray|; filter-not returns complement##||(filter #(> % 2) '(1 2 3)) _ _ ##gray|; remove returns complement##||(remove-if-not _ @<&nbsp;&nbsp;>@(lambda (x) (> x 2)) _ @<&nbsp;&nbsp;>@'(1 2 3)) _ _ ##gray|; remove-if returns complement##|| ||[#reduce reduce]||(reduce '- _ @<&nbsp;&nbsp;>@'(1 2 3 4) _ @<&nbsp;&nbsp;>@:initial-value 0)||(foldl (lambda (x y) (- y x)) 0 '(1 2 3 4))||(reduce - 0 '(1 2 3 4))||(reduce '- _ @<&nbsp;&nbsp;>@'(1 2 3 4) _ @<&nbsp;&nbsp;>@:initial-value 0)|| ||[#right-fold right fold]||(reduce '- _ @<&nbsp;&nbsp;>@'(1 2 3 4) _ @<&nbsp;&nbsp;>@:initial-value 0 _ @<&nbsp;&nbsp;>@:from-end t)||(foldr - 0 '(1 2 3 4))||##gray|//none//##||(reduce '- _ @<&nbsp;&nbsp;>@'(1 2 3 4) _ @<&nbsp;&nbsp;>@:initial-value 0 _ @<&nbsp;&nbsp;>@:from-end t)|| ||iterate||(dolist (x '(1 2 3)) _ @<&nbsp;&nbsp;>@(print x) _ @<&nbsp;&nbsp;>@(print (- x)))||(for ((x '(1 2 3))) _ @<&nbsp;&nbsp;>@(printf "~a~n" x) _ @<&nbsp;&nbsp;>@(printf "~a~n" (- x)))||(doseq [x '(1 2 3)] _ @<&nbsp;&nbsp;>@(println x) _ @<&nbsp;&nbsp;>@(println (- x)))||(dolist (x '(1 2 3)) _ @<&nbsp;&nbsp;>@(print x) _ @<&nbsp;&nbsp;>@(print (- x)))|| ||[#universal-predicate universal predicate]||(every _ @<&nbsp;&nbsp;>@(lambda (i) (= 0 (rem i 2))) _ @<&nbsp;&nbsp;>@'(1 2 3 4))||(for/and ((i '(1 2 3 4))) _ @<&nbsp;&nbsp;>@(= 0 (remainder i 2)))||(every? #(= 0 (rem % 2)) '(1 2 3 4))||(every _ @<&nbsp;&nbsp;>@(lambda (i) (= 0 (% i 2))) _ @<&nbsp;&nbsp;>@'(1 2 3 4))|| ||[#existential-predicate existential predicate]||(some _ @<&nbsp;&nbsp;>@(lambda (i) (= 0 (rem i 2))) _ @<&nbsp;&nbsp;>@'(1 2 3 4))||(for/or ((i '(1 2 3 4))) _ @<&nbsp;&nbsp;>@(= 0 (remainder i 2)))||(some #(= 0 (rem % 2)) '(1 2 3 4))||(some _ @<&nbsp;&nbsp;>@(lambda (i) (= 0 (% i 2))) _ @<&nbsp;&nbsp;>@'(1 2 3 4))|| ||list comprehension|| ||(for*/list _ @<&nbsp;&nbsp;>@((file "ABCDEFGH") (rank (in-range 1 9))) _ @<&nbsp;&nbsp;>@(format "~a~a" file rank))||(for _ @<&nbsp;&nbsp;>@[file "ABCDEFGH" rank (range 1 9)] _ @<&nbsp;&nbsp;>@(format "%c%d" file rank))|| || ||shuffle _ @<&nbsp;>@|| ||(shuffle '(1 2 3 4))||(shuffle '(1 2 3 4))|| || ||set head||(defparameter *a* '(1 2 3)) _ (setf (car *a*) 3)||(require schema/mpair) _ _ (define a (mlist 1 2 3)) _ (set-mcar! a 3)||##gray|//none//##||(setq a '(1 2 3) _ (setcar a 3)|| ||set tail||(defparameter *a* '(1 2 3)) _ (setf (cdr *a*) '(4 5 6))||(require schema/mpair) _ _ (define a (mlist 1 2 3)) _ (set-mcdr! a (mlist 4 5 6))||##gray|//none//##||(setq a '(1 2 3) _ (setcar a 3) _ (setcdr a '(4 5 6))|| ||manipulate back||(defparameter *a* '(1 2 3)) _ (push 4 *a*) _ (pop *a*)||##gray|//none//##|| ||(setq a '(1 2 3)) _ (push 4 a) _ (pop a)|| ||flatten|| ||(flatten '(1 2 (3 (4))))||(flatten '(1 2 (3 (4))))|| || ||associative array lookup _ @<&nbsp;>@||(assoc 3 '((1 2) (3 4)))||(assoc 3 '((1 2) (3 4)))||##gray|//none, see note//##||(assoc 3 '((1 2) (3 4)))|| ||flat associative array lookup _ @<&nbsp;>@||(getf '(1 2 3 4) 3)||##gray|//none//##||##gray|//none//##||(getf '(1 2 3 4) 3)|| ||[#pair-literal pair literal] _ @<&nbsp;>@||'(1 . 2)||'(1 . 2)||##gray|//none//##||'(1 . 2)|| ||cons cell test||(cons '(1 . 2)) _ (not (atom '(1 . 2)))||(cons? '(1 . 2)) _ (pair? '(1 . 2))||##gray|//none//##||(cons '(1 . 2)) _ (not (atom '(1 . 2)))|| ||translate elements recursively||(sublis '((1 . 2) (3 . 4)) _ @<&nbsp;&nbsp;>@'(1 (3 3 (1))))|| || ||(sublis '((1 . 2) (3 . 4)) _ @<&nbsp;&nbsp;>@'(1 (3 3 (1))))|| ||||||||||~ [# fixed-length-arrays](%23%20fixed-length-arrays.html)[#fixed-length-arrays-note fixed-length arrays]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[# fixed-len-array-literal](%23%20fixed-len-array-literal.html)[#fixed-len-array-literal-note literal] _ @<&nbsp;>@||#(1 2 3)||#(1 2 3)||[1 2 3]||[1 2 3]|| ||constructor _ @<&nbsp;>@||(vector 1 2 3)||(vector 1 2 3)||(vector 1 2 3)||(vector 1 2 3)|| ||size _ @<&nbsp;>@||(length #(1 2 3))||(vector-length #(1 2 3))||(count [1 2 3])||(length [1 2 3])|| ||lookup||(elt #(1 2 3) 0) ##gray|//or//## _ (aref #(1 2 3) 0)||(vector-ref #(1 2 3) 0)||(nth [1 2 3] 0)||(elt [1 2 3] 0)|| ||update||(setq v [1 2 3]) _ (setf (aref v 2) 4)||(define v (vector 1 2 3)) _ (vector-set! v 2 4)||(replace {2 4} [1 2 3])||(setq v #(1 2 3)) _ (setf (aref v 2) 4)|| ||out-of-bounds behavior||##gray|//raises// sb-kernel:index-too-large-error##||##gray|//error//##|| || || ||array to list _ @<&nbsp;>@||(coerce #(1 2 3) 'list)||(vector->list #(1 2 3))||(seq [1 2 3])||(coerce [1 2 3] 'list)|| ||list to array _ @<&nbsp;>@||(coerce '(1 2 3) 'vector)||(list->vector '(1 2 3))||(vec '(1 2 3))||(coerce '(1 2 3) 'vector)|| ||reverse||(reverse #(1 2 3))|| || || || ||sort||(sort #(2 4 1 3) #'<)|| || || || ||map||(map 'vector (lambda (x) (* x x)) #(1 2 3))|| || || || ||filter||(remove-if-not (lambda (x) (> x 2)) #(1 2 3)) _ _ ##gray|; also remove-if##|| || || || ||reduce|| || || || || ||||||||||~ [# dictionaries](%23%20dictionaries.html)[#dictionaries-note dictionaries]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[# dict-literal](%23%20dict-literal.html)[#dict-literal-note literal] _ @<&nbsp;>@||##gray|//none//##||##gray|; immutable:## _ #hash(("t" . 1) ("f" . 0))||##gray|; clojure.lang.PersistentArrayMap:## _ {"t" 1 "f" 0}||##gray|//none//##|| ||[# dict-ctor](%23%20dict-ctor.html)[#dict-ctor-note constructor]||(defparameter *h* (make-hash-table :test 'equal)) _ _ ##gray|; default equality test is 'eql##||(define ih _ @<&nbsp;&nbsp;>@(make-immutable-hash _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@'(("t" . 1) ("f" . 0)))) _ _ ##gray|; mutable:## _ (define h (make-hash '(("t" . 1) ("f" . 0))))||##gray|; immutable:## _ (def ih (hash-map "t" 1 "f" 0))||(setq h (make-hash-table :test 'equal))|| ||[# dict-pred](%23%20dict-pred.html)[#dict-pred-note predicate] _ @<&nbsp;>@||(hash-table-p *h*)||(hash? h) _ _ ##gray|; also true of assoc. lists and vectors:## _ (dict? h)||(map? ih)||(hash-table-p h)|| ||[# dict-size](%23%20dict-size.html)[#dict-size-note size] _ @<&nbsp;>@||(hash-table-count *h*)||(hash-count h) _ _ ##gray|; also works with assoc lists and vectors:## _ (dict-count ih)||(count ih)||(hash-table-count h)|| ||[# dict-lookup](%23%20dict-lookup.html)[#dict-lookup-note lookup] _ @<&nbsp;>@||(gethash "t" *h*)||(hash-ref h "t") _ _ ##gray|; return -1 if not found:## _ (hash-ref h "m" -1) _ _ ##gray|; also works with assoc. lists and vectors:## _ (dict-ref ih "t") _ (dict-ref ih "m" -1)||(get ih "t") _ (find ih "t") _ _ ##gray|; return -1 if not found:## _ (get ih "m" -1)||(gethash "t" h)|| ||[# dict-update](%23%20dict-update.html)[#dict-update-note update]||(setf (gethash "t" *h*) 1)||(hash-set! h "t" 2) _ _ (define ih2 (hash-set ih "t" 2)) _ _ ##gray|; also dict-set! and dict-set##||(def ih2 (assoc ih "t" 2)) ||(puthash "t" 1 h)|| ||[# dict-missing-key](%23%20dict-missing-key.html)[#dict-missing-key-note missing key behavior]||##gray|//returns// nil##||##gray|//error//##||##gray|//returns// nil##||##gray|//returns// nil##|| ||[# dict-is-key-present](%23%20dict-is-key-present.html)[#dict-is-key-present-note is key present] _ @<&nbsp;>@||(nth-value 1 (gethash "t" *h*))||(hash-has-key? h "t") _ _ ##gray|; also dict-has-key?##||(contains? ih "t")||##gray|//none//##|| ||[# dict-dele](%23%20dict-dele.html)[#dict-del-note delete]||(remhash "t" *h*)||(hash-remove! h "t") _ @<&nbsp;>@ _ (define ih2 _ @<&nbsp;&nbsp;>@(hash-remove ih "t")) _ _ ##gray|; also dict-remove! and dict-remove##||(def ih2 (dissoc ih "t"))||(remhash "hello" h)|| ||[# dict-merge](%23%20dict-merge.html)[#dict-merge-note merge]|| || ||##gray|; values in ih2 take precedence:## _ (define ih3 (merge ih ih2))|| || ||[# dict-invert](%23%20dict-invert.html)[#dict-invert-note invert]|| || ||(require 'clojure.set) _ _ (define ih4 (clojure.set/map-invert ih))|| || ||[# dict-iter](%23%20dict-iter.html)[#dict-iter-note iterate]|| (maphash _ @<&nbsp;&nbsp;>@(lambda (k v) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(print k) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(print v)) _ @<&nbsp;&nbsp;>@*h*)|| (hash-for-each h _ @<&nbsp;&nbsp;>@(lambda (k v) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(printf "~a~n" k) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(printf "~a~n" v))) _ _ ##gray|; also dict-for-each##||(doseq [p ih] _ @<&nbsp;&nbsp;>@(println (first p)) _ @<&nbsp;&nbsp;>@(println (second p)))||(maphash _ @<&nbsp;&nbsp;>@(lambda (k v) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(print k) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(print v)) _ @<&nbsp;&nbsp;>@h)|| ||[# dict-key-val-lists](%23%20dict-key-val-lists.html)[#dict-key-val-lists-note keys and values as lists]||##gray|//none//##||(hash-keys h) _ (hash-values h) _ _ ##gray|; also dict-keys and dict-values##||(def hkeys (map (fn [p] (first p)) ih)) _ (def hvals (map (fn [p] (second p)) ih))||##gray|//none//##|| ||||||||||~ [# user-defined-types](%23%20user-defined-types.html)[#user-defined-types-note user-defined types]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[#defstruct defstruct]||(defstruct account id balance)||(define-struct account (id (balance #:mutable)))||(defstruct account :id :balance)||(defstruct account id balance)|| ||[#struct struct]||(setq a _ @<&nbsp;&nbsp;>@(make-account _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@:id 3 _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@:balance 17.12))||(define a (make-account 3 17.12))||(def a (struct account 3 17.12))||(setq a _ @<&nbsp;&nbsp;>@(make-account :id 3 :balance 17.12))|| ||[#struct-getter struct getter] _ @<&nbsp;>@||(account-id a)||(account-id a)||(:id a)||(account-id a)|| ||[#struct-setter struct setter] _ @<&nbsp;>@||(setf (account-balance a) 0)||(set-account-balance! a 0)||##gray|//none//##||(setf (account-balance a) 0)|| ||[#struct-predicate struct predicate] _ @<&nbsp;>@||(account-p a)||(account? a)||##gray|//none//##||(account-p a)|| ||||||||||~ [# functions](%23%20functions.html)[#functions-note functions]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[#define-function define function] _ @<&nbsp;>@||(defun add (x y) (+ x y))||(define (add x y) (+ x y))||(defn add [x y] (+ x y))||(defun add (x y) (+ x y))|| ||can function and variable share name||##gray|//yes//##||##gray|//no//##||##gray|//no//##||##gray|//yes//##|| ||[#optional-argument optional argument]||(defun add (a &optional b) _ @<&nbsp;&nbsp;>@(if (null b) a (+ a b)))||(define (add a (b null)) _ @<&nbsp;&nbsp;>@(if (null? b) a (+ a b)))|| (defn add ([a] a) ([a b] (+ a b))) _ ##gray|//no syntax error if called with more than 2 args://## _ (defn add [a & [b]] _ @<&nbsp;&nbsp;>@(if (nil? b) a (+ a b)))||(defun add (a &optional b) _ @<&nbsp;&nbsp;>@(if (null b) a (+ a b)))|| ||[#variable-arguments variable number of arguments]||(defun add (a &rest b) _ @<&nbsp;&nbsp;>@(if (null b) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@a _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(+ a (eval (cons '+ b)))))||(define (add a . b) _ @<&nbsp;&nbsp;>@(if (null? b) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@a _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(+ a (apply + b))))||(defn add [a & b] _ @<&nbsp;&nbsp;>@(if (nil? b) a (+ a (apply + b))))||(defun add (a &rest b) _ @<&nbsp;&nbsp;>@(if (null b) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@a _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(+ a (eval (cons '+ b)))))|| ||[#default-value default value]||(defun add (a &optional (b 0)) _ @<&nbsp;&nbsp;>@(+ a b))||##gray|//racket://## _ (define (add a (b 0)) (+ a b))||(defn add _ @<&nbsp;&nbsp;>@([a] (add a 0)) _ @<&nbsp;&nbsp;>@([a b] (+ a b)))||##gray|//none//##|| ||[#named-parameter named parameter]||(defun logarithm (&key number base) _ @<&nbsp;&nbsp;>@(/ (log number) (log base))) _ @<&nbsp;>@ _ (logarithm :base 2 :number 8)||##gray|//none//##|| (defn logarithm [{x :number b :base}] (/ (Math/log x) (Math/log b))) _ (logarithm {:base 2 :number 8})||(defun logarithm _ @<&nbsp;&nbsp;>@(&key number &key base) _ @<&nbsp;&nbsp;>@(if base _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(/ (log number) (log base)) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(log number))) _ @<&nbsp;>@ _ ##gray|//order significant, not key names://## _ (logarithm :foo 8 :bar 2)|| ||[#return-multiple-values return multiple values]||(defun sqrts (x) _ @<&nbsp;&nbsp;>@(values (sqrt x) (- (sqrt x))))||(define (sqrts x) _ @<&nbsp;&nbsp;>@(values (sqrt x) (- (sqrt x))))||(defn sqrts [x] (list (Math/sqrt x) (- (Math/sqrt x))))||##gray|values //creates a list://## _ (defun sqrts (x) _ @<&nbsp;&nbsp;>@(values (sqrt x) (- (sqrt x))))|| ||[#multiple-values-local-variables assign multiple values to local variables]||(multiple-value-bind (r1 r2) _ @<&nbsp;&nbsp;>@(sqrts 3) _ @<&nbsp;&nbsp;>@r2)||(let-values _ @<&nbsp;&nbsp;>@(((r1 r2) (sqrts 3))) _ @<&nbsp;&nbsp;>@r2)||(let [[r1 r2] (sqrts 3)] r2)||(multiple-value-bind _ @<&nbsp;&nbsp;>@(r1 r2) _ @<&nbsp;&nbsp;>@(sqrts 3) _ @<&nbsp;&nbsp;>@r2)|| ||[#multiple-values-global-variables assign multiple values to global variables]||(multiple-value-setq (r1 r2) _ @<&nbsp;&nbsp;>@(sqrts 3))||(define-values (r1 r2) (sqrts 3))||##gray|//none//##||(multiple-value-setq (r1 r2) (sqrts 3))|| ||[#list-to-multiple-values convert list to multiple values]||(values-list '(1 2 3))||(apply values '(1 2 3))||##gray|//multiple values are lists//##||##gray|//multiple values are lists//##|| ||[#multiple-values-list assign multiple values to list]||(multiple-value-list (sqrts 3))||(call-with-values _ @<&nbsp;&nbsp;>@(lambda () (sqrts 3)) _ @<&nbsp;&nbsp;>@list)||##gray|//multiple values are lists//##||##gray|//multiple values are lists//##|| ||[#tail-call tail call optimization]||##gray|//yes for sbcl//##||##gray|//yes//##||##gray|//yes with//## recur||##gray|//no//##|| ||[#lambda lambda]||(lambda (x) (* x x))||(lambda (x) (* x x))||#(* % %) _ (fn [x] (* x x)) _ _ ##gray|; shortcut notation with two args:## _ #(* %1 %2)||(lambda (x) (* x x))|| ||[#apply apply]||((lambda (x) (* x x)) 2) _ @<&nbsp;>@ _ (apply #'(lambda (x) (* x x)) '(2))||((lambda (x) (* x x)) 2) _ @<&nbsp;>@ _ (apply (lambda (x) (* x x)) '(2))||(#(* % %) 2) _ @<&nbsp;>@ _ ((fn [x] (* x x)) 2) _ @<&nbsp;>@ _ (apply #(* % %) '(2))||((lambda (x) (* x x)) 2) _ @<&nbsp;>@ _ (apply _ @<&nbsp;&nbsp;>@#'(lambda (x) (* x x)) _ @<&nbsp;&nbsp;>@'(2))|| ||||||||||~ [# execution-control](%23%20execution-control.html)[#execution-control-note execution control]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[#progn progn] _ @<&nbsp;>@||progn prog1 prog2||begin ##gray|//none//## ##gray|//none//## _ ##gray|//r6rs://## _ begin begin0 ##gray|//none//##||do ##gray|//none//## ##gray|//none//##||progn prog1 prog2|| ||[#loop loop]||(setq i 1) _ (loop (print "hello") _ @<&nbsp;&nbsp;>@(if (> i 10) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(return) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(setq i (+ i 1))))||##gray|//none, use recursion//##||(loop [i 1] _ @<&nbsp;&nbsp;>@(if (<= i 10) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(do (println "hello") _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(recur (+ i 1)))))||(setq i 1) _ (loop (print "hello") _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(if (> i 10) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(return) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(setq i (+ i 1))))|| ||[#do do]||(do ((i 1) (sum 0)) _ @<&nbsp;&nbsp;>@((> i 100) sum) _ @<&nbsp;&nbsp;>@(setq sum (+ sum i)) _ @<&nbsp;&nbsp;>@(setq i (+ i 1))) _ ##gray|do* //initializes serially//##||##gray|//none//##||##gray|//none//##||(do ((i 1) (sum 0)) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@((> i 100) sum) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(setq sum (+ sum i)) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(setq i (+ i 1))) _ ##gray|do* //initializes sequentially//##|| ||[#dotimes dotimes]||(dotimes (i 10 nil) _ @<&nbsp;&nbsp;>@(format t "hello~%"))||##gray|//none//##||(dotimes [_ 10] _ @<&nbsp;&nbsp;>@(println "hello"))||(dotimes (i 10 nil) _ @<&nbsp;&nbsp;>@(print "hello\n"))|| ||[#if if] _ @<&nbsp;>@||(if (< x 0) (- x) x)||(if (< x 0) (- x) x)||(if (< x 0) (- x) x)||(if (< x 0) (- x) x)|| ||[#when when]||(when (< x y) _ @<&nbsp;&nbsp;>@(print "x is less ") _ @<&nbsp;&nbsp;>@(print "than y"))||##gray|//racket://## _ (when (< x y) _ @<&nbsp;&nbsp;>@(display "x is less ") _ @<&nbsp;&nbsp;>@(display "than y"))||(when (< x y) _ @<&nbsp;&nbsp;>@(println "x is less ") _ @<&nbsp;&nbsp;>@(println "than y"))||(when (< x y) _ @<&nbsp;&nbsp;>@(print "x is less ") _ @<&nbsp;&nbsp;>@(print "than y"))|| ||[#cond cond]||(cond ((> x 0) 1) _ @<&nbsp;&nbsp;>@((= x 0) 0) _ @<&nbsp;&nbsp;>@(t -1))||(cond ((> x 0) 1) _ @<&nbsp;&nbsp;>@((= x 0) 0) _ @<&nbsp;&nbsp;>@(else -1))||(cond (> x 0) 1 _ @<&nbsp;&nbsp;>@(= x 0) 0 _ @<&nbsp;&nbsp;>@true -1)||(cond ((> x 0) 1) _ @<&nbsp;&nbsp;>@((= x 0) 0) _ @<&nbsp;&nbsp;>@(t -1))|| ||[#lazy-evaluation lazy evaluation]|| ||(define x (delay (/ 1 0))) _ (promise? x) _ (+ 1 (force x))|| || || ||[#continuations continuations]|| ||(define cc null) _ (+ 1 (call/cc (lambda (x) (set! cc x) 0))) _ (cc 5)|| || || ||||||||||~ [# exceptions](%23%20exceptions.html)[#exceptions-note exceptions]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[#error error] _ @<&nbsp;>@||(error "failed")||(error "failed")||(throw (Exception. "failed"))||(error "failed")|| ||[#handle-error handle error]||(handler-case _ @<&nbsp;&nbsp;>@(error "failed") _ @<&nbsp;&nbsp;>@(simple-error (e) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(format t "error: ~a" e)))|| (with-handlers _ @<&nbsp;&nbsp;>@((exn:fail? _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;&nbsp;>@(lambda (e) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;&nbsp;>@(printf "error: ~a" _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;&nbsp;>@(exn-message e))))) _ @<&nbsp;&nbsp;>@(error "failed"))|| (try (throw (Exception. "failure")) _ @<&nbsp;&nbsp;>@(catch Exception e _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(printf "error: %s" _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(.getMessage e))))||(condition-case e _ @<&nbsp;&nbsp;>@(error "failed") _ @<&nbsp;&nbsp;>@(error (message "error: %s" _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(error-message-string e))))|| ||[#define-exception define exception]||(define-condition odd-err (error) _ @<&nbsp;&nbsp;>@((num :accessor odd-err-num _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@:initarg :num)) _ @<&nbsp;&nbsp;>@(:report _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(lambda (e s) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(format s "odd number: ~a" _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(odd-err-num e)))))||(define exn:odd-err? "odd number")|| ||##gray|//only symbols and keywords can be thrown and caught//##|| ||[#throw-exception throw exception]||(error 'odd-err :num 7)||(raise exn:odd-err?)||(throw (Exception. "failed"))||(throw 'odd-err t)|| ||[#catch-exception catch exception]||(handler-case (/ 1 0) _ @<&nbsp;&nbsp;>@(division-by-zero () _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(progn _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(format t "division by zero") _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@nil)))||(with-handlers ((exn:fail? (lambda (e) (begin (printf "division by zero~n") null)))) (/ 1 0))||(try (/ 1 0) (catch ArithmeticException _ (do (println "division by zero") nil)))||(catch 'failed (throw 'failed nil) t)|| ||[#restart-case restart-case]||(defun halve (l) _ @<&nbsp;&nbsp;>@(mapcar (lambda (x) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(restart-case _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(if (= (rem x 2) 0) (/ x 2) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(error 'odd-error :num x)) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(round-down () (/ (- x 1) 2)) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(round-up () (/ (+ x 1) 2)))) l))|| ||##gray|//none//##||##gray|//none//##|| ||[#invoke-restart invoke-restart]|| (handler-bind _ @<&nbsp;&nbsp;>@((odd-err _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(lambda (c) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(invoke-restart _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@'round-down)))) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(halve '(1 2 4 9)))|| ||##gray|//none//##||##gray|//none//##|| ||[#finally-clause finally clause]||(unwind-protect _ @<&nbsp;&nbsp;>@(error "failure") _ @<&nbsp;&nbsp;>@(print "clean up"))||##gray|//none//##||(try (throw (Exception. "failure")) _ @<&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;>@(finally (println "clean up")))||(unwind-protect _ @<&nbsp;&nbsp;>@(error "failure") _ @<&nbsp;&nbsp;>@(print "clean up"))|| ||||||||||~ [# streams](%23%20streams.html)[#streams-note streams]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[# std-file-handles](%23%20std-file-handles.html)[#std-file-handles-note standard file handles]||*standard-input* _ *standard-output* _ *error-output*||(current-input-port) _ (current-output-port) _ (current-error-port)||*in* _ *out* _ *err*|| || ||[# eof](%23%20eof.html)[#eof-note end-of-file behavior]||##gray|read-line //returns two values, the 2nd set to// T //at end-of-file.// _ _ EOF-OF-FILE //is signaled when reading past end of file.//##||##gray|//Returns the value// eof. _ _ //Use// eof-object? //to test for it.//##||##gray|.readLine //on a// java.io.Reader //object returns// nil.##|| || ||[# read-stdin](%23%20read-stdin.html)[#read-stdin-note read line from stdin]||(setq line (read-line))||(let ((s (read-line))) _ @<&nbsp;&nbsp;>@##gray|#|use s@@|#@@##)||(let [s (read-line)] _ @<&nbsp;&nbsp;>@##gray|(comment use s)##)|| || ||[# chomp](%23%20chomp.html)[#chomp-note chomp] _ @<&nbsp;>@|| ||##gray|read-line //discards newline//##||##gray|read-line //discards newline//##|| || ||[# println](%23%20println.html)[#println-note write line to stdout]||(defun println (s) _ @<&nbsp;&nbsp;>@(format t "~a~%" s)) _ @<&nbsp;>@ _ (println "hello")||(write-string s) _ (newline)||(println "hello")|| || ||[# format-stdout](%23%20format-stdout.html)[#format-stdout-note write formatted string to stdout]||(format t "~s ~d: ~2$~%" _ @<&nbsp;&nbsp;>@"foo" _ @<&nbsp;&nbsp;>@7 _ @<&nbsp;&nbsp;>@13.7)||(printf "~a ~a: ~a~n" _ @<&nbsp;&nbsp;>@"foo" _ @<&nbsp;&nbsp;>@7 _ @<&nbsp;&nbsp;>@(/ (round (* 13.7 100)) 100))||(printf "%s %d %.2f\n" "foo" 7 13.7)|| || ||[# open-file](%23%20open-file.html)[#open-file-note open file for reading]||(setq in (open "/etc/hosts"))||(let _ @<&nbsp;&nbsp;>@((f (open-input-file "/etc/hosts"))) _ @<&nbsp;&nbsp;>@##gray|#| use f @@|#@@##)||##gray|; f is java.io.Reader object:## _ (let [f (clojure.java.io/reader "/etc/hosts")] _ @<&nbsp;&nbsp;>@(.readLine f))|| || ||[# open-file-write](%23%20open-file-write.html)[#open-file-write-note open file for writing]||(setq out (open "/tmp/test" :direction :output :if-exists :supersede))||(let _ @<&nbsp;&nbsp;>@((f (open-output-file _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@"/tmp/foo" _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@#:exists 'truncate))) _ @<&nbsp;&nbsp;>@##gray|#| use f @@|#@@##)||##gray|; f is java.io.Writer object:## _ (let [f (clojure.java.io/writer "/tmp/foo")] _ @<&nbsp;&nbsp;>@(.write f "lorem ipsum\n") _ @<&nbsp;&nbsp;>@(.close f))|| || ||[# open-file-append](%23%20open-file-append.html)[#open-file-append-note open file for appending]||(setq out (open "/tmp/test" :direction :output :if-exists :append))||(let _ @<&nbsp;&nbsp;>@((f (open-output-file _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@"/tmp/foo" _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@#:exists 'append))) _ @<&nbsp;&nbsp;>@##gray|#| use f @@|#@@##)||(let [f (clojure.java.io/writer "/tmp/foo" _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@:append true)] _ @<&nbsp;&nbsp;>@(.write f "lorem ipsum\n") _ @<&nbsp;&nbsp;>@(.close f))|| || ||[# close-file](%23%20close-file.html)[#close-file-note close file] _ @<&nbsp;>@||(close in)||(close-input-port f) _ (close-output-port f)||(.close f)|| || ||[# close-file-implicitly](%23%20close-file-implicitly.html)[#close-file-implicitly-note close file implicitly]|| (with-open-file (out #P"/tmp/test" :direction :output) (write-line "lorem ipsum" out))||(call-with-input-file _ @<&nbsp;&nbsp;>@"/etc/hosts" _ @<&nbsp;&nbsp;>@(lambda (f) (##gray|#| use f @@|#@@##)) _ _ ##gray|; also call-with-output-file##||(with-open [f _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(clojure.java.io/reader "/etc/hosts")] _ @<&nbsp;&nbsp;>@##gray|(comment use f)##)|| || ||[# read-line](%23%20read-line.html)[#read-line-note read line] _ @<&nbsp;>@||(setq line (read-line f))||(define line (read-line in))||(.readLine f)|| || ||[# iterate-file](%23%20iterate-file.html)[#iterate-file-note iterate over file by line]|| ||(for ([line (in-lines _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(open-input-file _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@"/etc/hosts"))]) _ @<&nbsp;&nbsp;>@(write-string line) _ @<&nbsp;&nbsp;>@(newline))||(loop [line (.readLine f)] _ @<&nbsp;&nbsp;>@(if (not= line nil) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(do (println line) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(recur (.readLine f)))))|| || ||[# read-file-array](%23%20read-file-array.html)[#read-file-array-note read file into array of strings]|| ||##gray|; to list of strings:## _ (sequence->list (in-lines _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(open-input-file "/etc/hosts")))||(vec (line-seq f))|| || ||[# read-file-str](%23%20read-file-str.html)[#read-file-str-note read file into string]|| ||(define s (file->string "/etc/hosts"))|| (let [s (slurp "/etc/hosts")] _ @<&nbsp;&nbsp;>@(print s))|| || ||[# write-str](%23%20write-str.html)[#write-str-note write string] _ @<&nbsp;>@|| ||(write-string s f)||(.write f s)|| || ||[# write-line](%23%20write-line.html)[#write-line-note write line]|| ||(write-string s f) _ (newline f)||(.write f (println-str s))|| || ||[# flush-file](%23%20flush-file.html)[#flush-file-note flush file handle] _ @<&nbsp;>@|| ||(flush-output f)||(f .flush)|| || ||[# seek](%23%20seek.html)[#seek-note file handle position] _ _ ##gray|//get, set//##|| ||##gray|; Evaluates to non-negative integer:## _ (file-position f) _ _ ##gray|; Sets next read or write _ ; to beginning of file:## _ (file-position f 0)||##gray|; arg is characters from current position; _ ; moving backward not possible:## _ (.skip f 1000) _ _ ##gray|; arg is max characters to buffer:## _ (.mark f 1000000) _ ##gray|; move to position saved when .mark was called:## _ (.rest f)|| || ||[# in-memory-stream](%23%20in-memory-stream.html)[#in-memory-stream-note in memory stream]||(setq f (make-string-input-stream _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@"lorem ipsum")) _ (read-line f) _ _ (setq f2 (make-string-output-stream) _ (write-string "lorem ipsum) _ (get-output-stream-string out)||(define f (open-input-string "lorem ipsum")) _ (read-line f) _ _ (define f2 (open-output-string)) _ (write-string "lorem ipsum" f2) _ (get-output-string f2)||##gray|; use *in* to read from string:## _ (with-in-str "lorem ispum" _ @<&nbsp;&nbsp;>@(read-line)) _ _ ##gray|; use *out* to write to string:## _ (with-out-str _ @<&nbsp;&nbsp;>@(println "lorem ipsum"))|| || ||||||||||~ [# emacs-buffers](%23%20emacs-buffers.html)[#emacs-buffers-note emacs buffers]|| ||~ ||~ ||~ ||~ ||~ emacs lisp|| ||[# list-buffers](%23%20list-buffers.html)[#list-buffers-note list buffers]|| || || ||##gray|;; list of buffer objects:## _ (buffer-list) _ _ ##gray|;; name of first buffer in list:## _ (buffer-name (car (buffer-list))) _ _ ##gray|;; name of current buffer:## _ (buffer-name (current-buffer))|| ||[# current-buffer](%23%20current-buffer.html)[#current-buffer-note current buffer] _ ##gray|//get and set//##|| || || ||##gray|;; name of current buffer:## _ (buffer-name (current-buffer)) _ _ ##gray|;; open in current pane:## _ (switch-to-buffer "foo.txt") _ _ ##gray|;; open in other pane:## _ (switch-to-buffer-other-window _ @<&nbsp;&nbsp;>@"bar.txt")|| ||[# clear-buffer](%23%20clear-buffer.html)[#clear-buffer-note clear buffer]|| || || ||##gray|;; current buffer:## _ (erase-buffer) _ _ ##gray|;; buffer named "foo.txt:## _ (with-current-buffer "foo.txt" _ @<&nbsp;&nbsp;>@(erase-buffer))|| ||[# point](%23%20point.html)[#point-note point] _ ##gray|//get and set//##|| || || ||##gray|;; 1-based index of char under cursor:## _ (point) _ _ ##gray|;; go to beginning of current buffer:## _ (goto-char 1) _ _ ##gray|;; go to end of current buffer:## _ (goto-char (buffer-size))|| ||search and set point|| || || ||##gray|;; Set point to character after string. _ ;; 1st arg is position in buffer beyond _ ;;@<&nbsp;&nbsp;&nbsp;>@which search stops. _ ;; If 2nd arg is true, return nil _ ;;@<&nbsp;&nbsp;&nbsp;>@on failure, otherwise raise error. _ ;; 3rd argument is the occurrence _ ;;@<&nbsp;&nbsp;&nbsp;>@of the string, if negative _ ;;@<&nbsp;&nbsp;&nbsp;>@search backwards from point.## _ (search-forward "lorem" nil t 1)|| ||insert at string point|| || || ||##gray|;; takes 1 or more args:## _ (insert "lorem" " ipsum")|| ||current buffer as string|| || || ||(buffer-string)|| ||insert file contents at point|| || || ||(insert-file "/etc/passwd")|| ||[# mark](%23%20mark.html)[#mark-note mark] _ ##gray|//get and set//##|| || || ||##gray|;; to beginning of current buffer:## _ (set-mark 1) _ _ ##gray|;; to point of current buffer:## _ (set-mark (point))|| ||||||||||~ [# files](%23%20files.html)[#files-note files]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[# file-test](%23%20file-test.html)[#file-test-note file test, regular file test]||(osicat:file-exists-p "/tmp/foo") _ (osicat:regular-file-exists-p "/tmp/foo")||##gray|//??//## _ (file-exists? "/etc/hosts")||(.exists (io/file "/etc/hosts"))||(file-exists-p "/etc/hosts") _ _ (file-regular-p "/etc/hosts")|| ||[# file-size](%23%20file-size.html)[#file-size-note file size]|| ||(file-size "/etc/hosts")||(.length (io/file "/etc/hosts"))||(eighth _ @<&nbsp;&nbsp;>@(file-attributes "/etc/hosts"))|| ||[# file-readable-writable-executable](%23%20file-readable-writable-executable.html)[#file-readable-writable-executable-note is file readable, writable, executable]|| ||(pair? (filter _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(lambda (x) (eq? x 'read)) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(file-or-directory-permissions _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@"/etc/hosts"))) _ (pair? (filter _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(lambda (x) (eq? x 'write)) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(file-or-directory-permissions _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@"/etc/hosts"))) _ (pair? (filter _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(lambda (x) (eq? x 'execute)) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(file-or-directory-permissions _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@"/etc/hosts")))||(.canRead (io/file "/etc/hosts")) _ (.canWrite (io/file "/etc/hosts")) _ (.canExecute (io/file "/etc/hosts"))|| || ||[# chmod](%23%20chmod.html)[#chmod-note set file permissions]|| ||(file-or-directory-permissions _ @<&nbsp;&nbsp;>@"/tmp/foo" _ @<&nbsp;&nbsp;>@#o755)|| ||(set-file-modes "/tmp/foo" #o755)|| ||[# last-modification-time](%23%20last-modification-time.html)[#last-modification-time-note last modification time]|| ||(file-or-directory-modify-seconds "/tmp/foo")||##gray|; Unix epoch in milliseconds:## _ (.lastModified (java.io.File. "/tmp/foo"))|| || ||[# cp-rm-mv](%23%20cp-rm-mv.html)[#cp-rm-mv-note copy file, remove file, rename file]||(cl-fad:copy-file #P"/tmp/foo" _ @<&nbsp;&nbsp;>@#P"/tmp/bar") _ _ (delete-file #P"/tmp/foo") _ _ (rename-file #P"/tmp/bar" _ @<&nbsp;&nbsp;>@#P"/tmp/foo")||(copy-file "/tmp/foo" "/tmp/bar") _ (delete-file "/tmp/foo") _ (rename-file-or-directory _ @<&nbsp;&nbsp;>@"/tmp/bar" _ @<&nbsp;&nbsp;>@"/tmp/foo")||(clojure.java.io/copy _ @<&nbsp;&nbsp;>@(java.io.File. "/tmp/foo") _ @<&nbsp;&nbsp;>@(java.io.File. "/tmp/bar")) _ (clojure.java.io/delete-file "/tmp/foo") _ (.renameTo (java.io.File. "/tmp/bar") _ @<&nbsp;&nbsp;>@(java.io.File. "/tmp/foo"))||(copy-file "/tmp/foo" "/tmp/bar") _ (delete-file "/tmp/foo") _ (rename-file "/tmp/bar" "/tmp/foo")|| ||[# symlink](%23%20symlink.html)[#symlink-note create symlink, symlink test, get target]||(osicat:make-link "/tmp/hosts" :target "/etc/hosts")||(make-file-or-directory-link _ @<&nbsp;&nbsp;>@"/etc/hosts" _ @<&nbsp;&nbsp;>@"/tmp/hosts") _ (link-exists? "/tmp/hosts") _ ##gray|//??//##|| ||(make-symbolic-link "/etc/hosts" /tmp/hosts") _ ##gray|//returns target if symlink or nil://## _ (file-symlink-p "/tmp/hosts")|| ||[# tmp-file](%23%20tmp-file.html)[#tmp-file-note temporary file]|| ||(define tmp (make-temporary-file)) _ (path->string tmp)||##gray|; java.io.File:## _ (java.io.File/createTempFile "foo" ".txt")||(make-temp-file "foo")|| ||||||||||~ [# directories](%23%20directories.html)[#directories-note directories]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[# build-pathname](%23%20build-pathname.html)[#build-pathname-note build pathname]||(make-pathname _ @<&nbsp;&nbsp;>@:directory '(:absolute "etc") _ @<&nbsp;&nbsp;>@:name "hosts")||##gray|; returns path; convert to string _ ; with path->string:## _ (build-path "/etc" "hosts")||(require '[clojure.java.io :as io]) _ _ ##gray|; returns java.io.File; _ ; convert to string with .getPath:## _ (io/file "/etc" "hosts")|| || ||[# dirname-basename](%23%20dirname-basename.html)[#dirname-basename-note dirname and basename]||(pathname-directory #P"/etc/hosts") _ _ (pathname-name #P"/etc/hosts")||(let-values (((dir file _) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(split-path "/etc/hosts"))) _ @<&nbsp;&nbsp;>@##gray|#| use dir or file @@|#@@##)||(require '[clojure.java.io :as io]) _ _ (.getParent (io/file "/etc/hosts")) _ (.getName (io/file "/etc/hosts"))||(file-name-directory "/etc/hosts") _ _ (file-name-nondirectory _ @<&nbsp;&nbsp;>@"/etc/hosts")|| ||[# abs-pathname](%23%20abs-pathname.html)[#abs-pathname-note absolute pathname]|| ||(simplify-path _ @<&nbsp;&nbsp;>@(path->complete-path ".."))||(.getCanonicalPath (java.io.File. ".."))||(expand-file-name "..")|| ||[# iterate-dir](%23%20iterate-dir.html)[#iterate-dir-note iterate over directory by file]||(dolist (file (osicat:list-directory "/tmp")) (format t "~a~%" file))||(for ([path (directory-list "/etc")]) _ @<&nbsp;&nbsp;>@(write-string _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(path->string path)))||##gray|; file-seq returns java.io.File objects for files _ ; in arg directory and any subdirs recursively.## _ (filter #(= (.getParent %) "/etc") _ @<&nbsp;&nbsp;>@(file-seq (clojure.java.io/file "/etc")))||(dolist _ @<&nbsp;&nbsp;>@(file (directory-files "/etc")) _ @<&nbsp;&nbsp;>@(print file)))|| ||[# mkdir](%23%20mkdir.html)[#mkdir-note make directory]|| ||(make-directory* "/tmp/foo/bar")||(require '[clojure.java.io :as io]) _ _ (.mkdir (io/file "/tmp/foo"))||##gray|//creates parents if 2nd arg non-nil://## _ (make-directory "/tmp/foo/bar" t)|| ||[# recursive-cp](%23%20recursive-cp.html)[#recursive-cp-note recursive copy]|| ||(copy-directory/files "/tmp/foo.d" _ @<&nbsp;&nbsp;>@"/tmp/bar.d")|| || || ||[# rmdir](%23%20rmdir.html)[#rmdir-note remove empty directory]||(delete-directory "/tmp/foo.d")||(delete-directory "/tmp/foo.d")||(clojure.java.io/delete-file "/tmp/foo.d")||(delete-directory "/tmp/foo.d")|| ||[# rm-rf](%23%20rm-rf.html)[#rm-rf-note remove directory and contents]|| (osicat:delete-directory-and-files "/tmp/foo.d")||(delete-directory/files "/tmp/foo.d")|| ||(delete-directory "/tmp/foo.d" t)|| ||[# dir-test](%23%20dir-test.html)[#dir-test-note directory test]||(osicat:directory-exists-p #P"/etc")||(directory-exists? "/etc")||(.isDirectory (io/file "/etc"))||(file-directory-p "/etc")|| ||||||||||~ [# processes-environment](%23%20processes-environment.html)[#processes-environment-note processes and environment]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[# cmd-line-arg](%23%20cmd-line-arg.html)[#cmd-line-arg-note command line arguments]||*posix-argv*||current-command-line-arguments||*command-line-args*||##gray|//in shebang mode only://## _ command-line-args ##gray|//or//## argv|| ||[# program-name](%23%20program-name.html)[#program-name-note program name]|| || || || || ||[# env-var](%23%20env-var.html)[#env-var-note environment variables]||(posix-getenv "HOME")||(getenv "HOME")||(System/getenv "HOME")||(getenv "HOME")|| ||[# user-id-name](%23%20user-id-name.html)[#user-id-name-note user id and name]|| || || || || ||[# exit](%23%20exit.html)[#exit-note exit]|| || || || || ||[# external-cmd](%23%20external-cmd.html)[#external-cmd-note external command]||(run-program "ls" '( "/etc"))||(require scheme/system) _ (system "ls /etc")||(.exec (Runtime/getRuntime) "ls")||(shell-command "ls /etc")|| ||[# cmd-subst](%23%20cmd-subst.html)[#cmd-subst-note command substitution]|| || || ||(shell-command-to-string "ls /etc")|| ||||||||||~ [# libraries-namespaces](%23%20libraries-namespaces.html)[#libraries-namespaces-note libraries and namespaces]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||complete example|| || ||$ cat b/a.clj _ (ns b.a) _ (def x 3) _ _ $ java -cp clojure.jar:. clojure.main _ => (require 'b.a) _ => b.a/x _ 3|| || ||compile library||(compile-file "a.lisp")||$ raco make a.rkt||(compile 'a)||$ emacs -batch -Q -L . \ _ @<&nbsp;&nbsp;>@-f batch-byte-compile a.el|| ||load library _ @<&nbsp;>@||(load "a.lisp")||(require a)||(require 'a)||(require "a")|| ||load library in subdirectory||(load "b/a.lisp")||(require "b/a.rkt")||(require 'b.a)|| || ||hot patch||(load "a.lisp")||##gray|//none//##||(require 'b.a :reload)||(load "a")|| ||load error||##gray|//raises// sb-int:simple-file-error##||##gray|//raises// exn:fail:syntax:missing-module. //Because// require //must be top-level, the exception cannot be handled.//##||##grya|//raises// FileNotFoundException##||##gray|//raises// file-err##|| ||library path||##gray|//contains working directory at startup//##||(require setup/dirs) _ _ (get-collects-search-dirs)||##gray|//same as path used by java VM//##||##gray|; adds directory to library path:## _ (add-to-list 'load-path ("/home/ed/.emacs.d/lib"))|| ||library path environment variable||##gray|//none//##|| ||##gray|CLASSPATH##||##gray|EMACSLOADPATH##|| ||library path command line option||##gray|//none//##|| ||$ java -cp /foo/bar:/baz/quux||$ emacs -L /foo/bar|| ||namespace declaration||(defpackage :foo)||(module mconst racket _ @<&nbsp;&nbsp;>@(provide pi) _ @<&nbsp;&nbsp;>@(define pi 3.14))||(ns mconst)||##gray|//No namespaces; a common convention is to use a prefix on all identifiers in a library, separated from the rest of the identifier by a hyphen.//##|| ||subnamespace declaration||##gray|//none//##|| ||##gray|; must be in b/a.clj:## _ (ns b.a)|| || ||namespace separator||:||:||. ##gray|//and//## /|| || ||import definitions||##gray|; set current *package* to foo and import symbol twiddle from bar:## _ (defpackage :foo _ @<&nbsp;&nbsp;>@(:import-from :bar :twiddle))|| || || || ||import all definitions in namespace||##gray|; set current *package* to foo and import symbols from bar:## _ (defpackage :foo _ @<&nbsp;&nbsp;>@(:use :bar))|| || || || ||namespace shadow avoidance|| || || || || ||identifier shadow avoidance|| || || || || ||package manager help|| ||$ raco help _ $ raco pkg @@--@@help _ $ raco pkg install @@--@@help|| || || ||list installed packages|| ||$ raco pkg show @@--@@all|| ||M-x list packages|| ||search packages||(ql:system-apropos "time")||[http://pkgs.racket-lang.org http://pkgs.racket-lang.org]|| ||M-x list-packages|| ||install package||##gray|; install quicklisp## _ (load "~/quicklisp/setup.lisp") _ (ql:quickload "osicat")||$ raco pkg install @@--@@deps search-auto srfi|| ||##gray|//Use// M-x list-packages //to bring up the package menu;// i //to select a package to install, and// x //to install it.//##|| ||remove package|| ||$ raco pkg remove srfi|| ||##gray|//In the package menu, use// d //to select a package to uninstall and// x //to uninstall it.//##|| ||||||||||~ [# objects](%23%20objects.html)[#objects-note objects]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[#defclass define class]||(defclass rectangle () _ @<&nbsp;&nbsp;>@( _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(height _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@:accessor rectangle-height _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@:initarg :height) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(width _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@:accessor rectangle-width _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@:initarg :width)))||(define rectangle% _ @<&nbsp;&nbsp;>@(class object% _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(init width) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(init height) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(super-new) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(define curr-height height) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(define curr-width width) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(define/public (get-height) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@curr-height) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(define/public (get-width) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@curr-width) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(define/public (set-height ht) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(set! curr-height ht)) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(define/public (set-width wd) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(set! curr-width wd))))||##gray|//use java://## _ public class Rectangle { _ @<&nbsp;&nbsp;>@public float height; _ @<&nbsp;&nbsp;>@public float width; _ @<&nbsp;&nbsp;>@public Rectangle(float h, float w) { _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@this.height = h; _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@this.width = w; _ @<&nbsp;&nbsp;>@} _ @<&nbsp;&nbsp;>@public void setHeight(float h) { _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@this.height = h; _ @<&nbsp;&nbsp;>@} _ @<&nbsp;&nbsp;>@public void setWidth(float w) { _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@this.width = w; _ }|| || ||[#make-instance make instance]||(make-instance 'rectangle _ @<&nbsp;&nbsp;>@:height 3 _ @<&nbsp;&nbsp;>@:width 7)||(define rect _ @<&nbsp;&nbsp;>@(new rectangle _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(height 7) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(width 3)))||(import 'Rectangle) _ (def r (Rectangle. 7 3))|| || ||[#read-attribute read attribute] _ @<&nbsp;>@||(rectangle-height rect)||(send rect get-height)||(.height r)|| || ||[#write-attribute write attribute] _ @<&nbsp;>@||(setf (rectangle-height rect) 4)||(send rect set-height 4)||(.setHeight r 8)|| || ||[#defmethod define method]||(defmethod area ((figure rectangle)) _ @<&nbsp;&nbsp;>@(* (rectangle-height figure) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(rectangle-width figure)))||(define/public (area) _ @<&nbsp;&nbsp;>@(* curr-height curr-width))||(defmulti area class) _ (defmethod area Rectangle [r] (* (.height r) (.width r)))|| || ||[#invoke-method invoke method] _ @<&nbsp;>@||(area rect)||(send rect area)||(area r)|| || ||[#universal-superclass universal superclass]||standard-object t||object%||Object|| || ||[#multiple-inheritance multiple inheritance]||yes||no||##gray|//only one direct superclass; can implement multiple interfaces//##|| || ||||||||||~ [# lisp-macros](%23%20lisp-macros.html)[#lisp-macros-note lisp macros]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[#backquote-comma backquote and comma]||(setq op '+) _ (eval @@@@(,op 1 1))||(define op ‘+) _ (eval @@@@(,op 1 1)) _ (eval (quasiquote ((unquote op) 1 1)))||(def op +) _ (eval @@@@(,op 1 1))||(setq op ‘+) _ (eval @@@@(,op 1 1))|| ||[#defmacro defmacro]||(defmacro rpn (arg1 arg2 op) _ @<&nbsp;&nbsp;>@(list op arg1 arg2))||(define-syntax-rule (rpn arg1 arg2 op) (op arg1 arg2))||(defmacro rpn [arg1 arg2 op] _ @<&nbsp;&nbsp;>@(list op arg1 arg2))||(defmacro rpn (arg1 arg2 op) _ @<&nbsp;&nbsp;>@(list op arg1 arg2))|| ||[#defmacro-backquote defmacro w/ backquote]||(defmacro rpn (arg1 arg2 op) _ @<&nbsp;&nbsp;>@@@@@(,op ,arg1 ,arg2))||(define-syntax-rule (rpn3 arg1 arg2 op) _ @<  >@(eval (,op ,arg1 ,arg2)))||(defmacro rpn [arg1 arg2 op] @@@@(~op ~arg1 ~arg2))||(defmacro rpn (arg1 arg2 op) _ @<  >@@@@@(,op ,arg1 ,arg2))|| ||[#macro-predicate macro predicate]||(macro-function rpn)||##gray|//none//##||##gray|//none//##||##gray|//none//##|| ||[#macroexpand macroexpand]||(macroexpand '(rpn 1 2 +))||(syntax-object->datum (expand-to-top-form '(rpn 1 2 +)))||(macroexpand '(rpn 1 2 +))||(macroexpand '(rpn 1 2 +))|| ||[#splice-quote splice quote]||(defmacro add ( &rest args ) _ @<&nbsp;&nbsp;>@@@@@(+ ,@args))||(define-syntax-rule ( add first …) (+ first …))||(defmacro add [ & args ] @@@@(+ ~@args))||(defmacro add ( &rest args ) _ @<&nbsp;&nbsp;>@@@@@(+ ,@args))|| ||[#recursive-macro recursive macro]||(defmacro add (a &rest b) _ @<  >@@@@@(if (null ',b) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(+ ,a) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(+ ,a (add ,@b))))||(define-syntax add (syntax-rules () _ @<&nbsp;&nbsp;>@[(add x) x] _ @<&nbsp;&nbsp;>@[(add x y) (+ x y)] _ @<&nbsp;&nbsp;>@[(add x y ...) (+ x (add y ...))]))||(defmacro add ([a] @@@@(+ ~a)) ([a & b] @@@@(+ ~a (add ~@b))))||(defmacro add (a &rest b) _ @<&nbsp;&nbsp;>@@@@@(if (null ‘,b) _ @<  >@@<  >@(+ ,a) _ @<  >@@<  >@(+ ,a (add ,@b))))|| ||[#hygienic hygienic] _ @< >@||##gray|//no//##||##gray|//yes//##||##gray|//with// # //suffix//##||##gray|//no//##|| ||[#local-values local values]||(defmacro square-sum (x y) _ @<  >@(let ((sum (gensym))) _ @<  >@@<  >@@@@@(let ((,sum (+ ,x ,y))) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(* ,sum ,sum))))||(define-syntax-rule (square-sum x y) _ @<&nbsp;&nbsp;>@(let ((sum (+ x y))) _ @<&nbsp;&nbsp;>@@<&nbsp;&nbsp;>@(* sum sum)))||(defmacro two-list [x] @@@@(let arg# ~x))||(defmacro square-sum (x y) _ @<  >@(let ((sum (gensym))) _ @<  >@@<  >@@@`@@(let ((,sum (+ ,x ,y))) _ @<  >@@<  >@@<  >@(* ,sum ,sum))))|| ||||||||||~ # reflection[#reflection-note reflection]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||inspect type _ @< >@||(type-of ‘(1 2 3)) _ (typep ‘(1 2 3) ‘list) _ (listp ‘(1 2 3))||(list? ‘(1 2 3))||(= (type 1) java.lang.Long) _ (= (class 1) java.lang.Long) _ (integer? 1)||(type-of [1 2 3] ‘vector) _ (typep [1 2 3] ‘vector) _ (vectorp [1 2 3])|| ||instance-of|| || ||instance?|| || ||basic types||##gray|//logical and numeric://## _ bignum bit complex double-float fixnum float integer long-float nil null number ratio rational real short-float signed-btye single-float t unsigned-byte _ _ ##gray|//symbols and strings://## _ base-character character extended-character keyword simple-string standard-char string symbol _ _ ##gray|//data structures://## _ array atom bit-vector cons hash-table list sequence simple-array simple-bit-vector simple-vector vector _ _ ##gray|//other://## _ compiled-function function package pathname random-state stream|| || || || ||[#sequence-data-types sequence data types]||list vector||list vector hash-table string input-port range||all collections and strings||list vector|| ||# docstring[#docstring-note get docstring] _ @< >@||(describe #’mapcar)||##gray|//none//##||(doc map)||(describe-function ‘mapcar)|| ||# define-docstring[#define-docstring-note define function with docstring]||(defun add (x y) _ @<  >@"add x and y” _ @<  >@(+ x y))||##gray|//none//##||(defn add “add x and y” [x y] _ @<  >@(+ x y))||(defun add (x y) _ @<  >@"add x and y” _ @<  >@(+ x y))|| ||# search-doc[#search-doc-note apropos and documentation search]||##gray|//none//##||##gray|//none//##||(apropos #”^add$”) _ (find-doc #"add \S+ and \S+”)||(apropos “^add$”) _ ##gray|//none//##|| ||||||||||~ # java-interop[#java-interop-note java interoperation]|| ||~ ||~ common lisp||~ racket||~ clojure||~ emacs lisp|| ||[#java-new new]|| || ||(def rnd (new java.util.Random)) _ (def rnd (java.util.Random.))|| || ||[#java-method method]|| || ||(. rnd nextFloat) _ (.nextFloat rnd) _ (. rnd nextInt 10) _ (.nextInt rnd 10)|| || ||[#java-class-method class method] _ @< >@|| || ||(Math/sqrt 2)|| || ||[#java-chain chain] _ @< >@|| || || || || ||[#java-import import]|| || ||(import ‘(java.util Random)) _ (def rnd (Random.))|| || ||[#java-to-array to java array]|| || ||(to-array ‘(1 2 3)) _ (into-array Integer ‘(1 2 3))|| || ||~ ||~ ##EFEFEF|@@_______________________________________@@##||~ ##EFEFEF|@@____________________________________@@##||~ ##EFEFEF|@@____________________________________@@##||~ ##EFEFEF|@@_______________________________________@@##||

# version-used-note ++ [#version-used version used]

Versions used to verify examples in the reference sheet.

# show-version-note ++ [#show-version show version]

How to determine the version.

# grammar-execution-note + [#grammar-execution Grammar and Execution]

# compiler-note ++ [#compiler compiler]

racket

Compiling a.ss creates the byte-code compiled file a_ss.zo, which will be used by //mzscheme// in preference to the source code if it encounters

code (require a) /code

# standalone-executable-note ++ [#standalone-executable standalone executable]

racket

In order for code to be compiled as a standalone executable, it must be packaged as a module. This can be accomplished by putting the //#lang scheme// shorthand the top of the file. All functions that are defined in the module will be executed in order. Here is a simple example:

code #lang scheme (define hello (printf “Hello world!~n”)) /code

emacs

[http://www.gnu.org/s/emacs/manual/html_node/elisp/Building-Emacs.html Building Emacs]

# interpreter-note ++ [#interpreter interpreter]

How to interpret the code in a file.

# shebang-note ++ [#shebang shebang]

How to have a script run by the interpreter automatically. Replace the given path with the path to the interpreter on your system.

emacs lisp

To run some lisp code from within emacs, use //M-x load// or //M-x load-file//. The first command will use the list of strings in //load-path// to search for the file. It is not necessary to specify the //.el// or //.elc// suffix if the file has one.

The following snippet is an emacs lisp shebang script implementation of //cat//:

code #!/usr/bin/env emacs –script (condition-case nil (let (line) (while (setq line (read-from-minibuffer ““)) (princ line) (princ “\n”))) (error nil)) /code

An implementation of //echo//:

code #!/usr/bin/env emacs –script (condition-case nil (progn (dotimes (i (length argv) nil) (princ (nth i argv)) (princ “ “)) (princ “\n”)) (error nil)) /code

# repl-note ++ [#repl repl]

How to invoke the repl from the command line.

racket:

Racket also provides a GUI repl environment called DrRacket.

clojure:

The clojure repl saves the result of each evaluation in the variables *1, *2, … and the last exception in *e.

# cmd-line-prog-note ++ [#cmd-ilne-prog command line program]

How to pass in a program to be executed on the command line.

# word-separator-note ++ [#word-separator word separator]

What is used to separate the operator and data of a S-expression.

# identifier-char-note ++ [#identifier-char identifier characters]

In lisps other than clojure, any character can be used in a symbol. Some characters are special to the reader and must be escaped to include them in a symbol. The reader will interpret a sequence of characters starting with a digit as a number instead of a symbol, so escaping must be used to create such a symbol.

common lisp:

Common Lisp is case insensitive, and the reader converts all letters to upper case. A symbol consisting of just periods “.” must be escaped. Symbols that start and end with an asterisk “*” may conflict with system defined special variables.

racket:

@@#@@ is only disallowed by the reader at the beginning of symbols. A symbol consisting of a single period must be escaped.

# eol-comment-note ++ [#eol-comment end-of-line comment]

# multiple-line-comment-note ++ [#multiple-line-comment multiple line comment]

#| |# delimited comments in Common Lisp and Scheme can span multiple lines, and thus can be used to comment out code.

clojure:

Code with balanced parens can be commented out in the following manner:

code (comment (+ 1 1) ) /code

# var-expr-note + [#var-expr Variables and Expressions]

# id-note ++ [#id identifier]

Are identifiers case sensitive; which characters can be used in identifers.

In Lisp, identifiers are called //symbols//.

# quoted-id-note ++ [#quoted-id quoted identifer]

How to quote or escape characters in identifiers which are otherwise prohibited.

# local-var-note ++ [#local-var local variable]

How to declare a local variable.

# global-var-note ++ [#global-var global variable]

How to declare a global variable.

# rm-var-note ++ [#rm-var remove variable]

How to remove a variable.

# null-note ++ [#null null]

The null value.

common lisp

{{nil}} and the empty list {{’()}} are identical.

racket

{{null}} and the empty list {{’()}} are identical.

clojure

{{nil}} and the empty list {{’()}} are distinct.

emacs lisp

{{nil}} and the empty list {{’()}} are identical.

# null-test-note ++ [#null-test null test]

How to test whether a value is null.

# id-as-val-note ++ [#id-as-val identifier as value]

How to get the value of an identifier.

In Lisp, identifiers are first class values and can be stored in variables. When used as an argument, the Lisp interpreter will treat an identifier as the value of the variable associated with the identifier unless special syntax is used.

# id-test-note ++ [#id-test identifier test]

How to test whether a value is an identifier.

# non-referential-id-note ++ [#non-referential-id non-referential identifier]

A non-referential identifier is an identifier whose value is itself.

Non-referential identifiers are called //keywords// in Lisp. They also appear in Prolog, where they are called //atoms//, and Ruby, where they are called //symbols//.

A non-referential identifier can be convenient to use as a key in a dictionary, since it doesn’t have to single quote escaped.

Strings are an alternative to non-referential identifiers; some languages have string interning which makes the use of strings just as efficient as non-referential identifiers.

# id-attr-note ++ [#id-attr identifier attributes]

In Common Lisp, there is a dictionary of attributes associated with each identifier called a //property list//.

Clojure //metadata// is stored with a value which is an instance of {{clojure.lang.IObj}}. Many types are subclasses of {{clojure.lang.IObj}}, but integers, floats, and strings are not. Clojure metadata is immutable: all keys must be set at once and there is no way to remove keys.

# cell-types ++ cell types

The different cell types. A lisp-1 only stores a single entity under a symbol in a given environment. A lisp-2 stores multiple entities, and which entity a symbol will resolve to depends on how the symbol is used. In particular, a value and a function can be stored under the same symbol without collision.

# nil ++ nil, is () null?, is () symbol?

code (eq nil ()) /code

is true in common lisp and emacs lisp.

code (eq? () null) /code

is true in Scheme.

# keyword ++ keyword

Keywords are pre-defined symbols that evaluate to their printed representation. The reader recognizes them by the initial colon, or in the case of Scheme, by the initial “#:”. In Scheme it is an error to use a keyword as an expression.

# atom ++ atom

//atom// is is a predicate which returns false for cons cells, and true for anything else. All lists except for the empty list are cons cells.

racket

Scheme lacks //atom//, but //cons?// is its logical negation.

clojure

Clojure lacks cons cells. Thus //atom// if implemented in the language would always return true. However, //(not (list? x))// is closer to the spirit and certainly more useful. Because //nil// is not the empty list in clojure there is also ambiguity about what the value of //(atom ())// would be.

# quote ++ quote

All lisps have a single quote macro abbreviation for //quote//. Here are identical ways to quote a symbol and a list:

code (quote a) ‘a

(quote (+ 3 7)) ‘(+ 3 7) /code

//eval// is a one-sided inverse of //quote//. If X is arbitrary lisp code, then the following are identical code X (eval (quote X)) /code

# eq ++ eq, equal, =

In his 1960 paper, McCarthy described //eq// as undefined if either or both arguments are not atomic. Common Lisp and Scheme (eq?) return true if the arguments both evaluate to the same list in memory, otherwise false. //equal// and //equal?// (Scheme) return true if the arguments evaluate to lists with the same elements as determined by calling //equal// or //equal?// recursively.

In Common Lisp and Scheme, = can only be called on numeric arguments. The predicates for whether a symbol is numeric are //numberp// and //number?//, respectively.

Clojure dispenses with //eq// and //equal// and defines //=// to be equivalent to the Common Lisp //equal//.

# car ++ car

Because //car// and //cdr// are abbreviations for parts of the word of the IBM 704, there is a trend to replace them with //first// and //rest//. However, //car// and //cdr// are short, and convenient notation exists for abbreviating nested calls to //car// and //cdr//.

In terms of //car//, //cdr//, and combinations thereof, here is what the dialects define:

||~ common lisp||~ r5rs||~ racket||~ clojure||~ emacs lisp|| ||car,first||car||car,first||first||car,first|| ||cadr,second||cadr||cadr,second||second,fnext||cadr,second|| ||caddr,third||caddr||caddr,third|| ||caddr,third|| ||cadddr,fourth||cadddr||cadddr,fourth|| ||cadddr,fourth|| ||fifth|| ||fifth|| ||fifth|| ||sixth|| ||sixth|| ||sixth|| ||seventh|| ||seventh|| ||seventh|| ||eighth|| ||eighth|| ||eighth|| ||ninth|| ||ninth|| ||ninth|| ||tenth|| ||tenth|| ||tenth|| ||cdr, rest||cdr||cdr, rest||rest,next||cdr, rest|| ||cddr||cddr||cddr|| ||cddr|| ||cdddr||cdddr||cdddr|| ||cdddr|| ||cddddr||cddddr||cddddr|| ||cddddr|| ||caar ||caar||caar||ffirst||caar|| ||cdar||cdar||cdar||nfirst||cdar||

# cdr ++ cdr

common lisp

//cdr// and //rest// return //nil// when called on an empty list.

racket

//cdr// and //rest// raise an error when called on an empty list.

clojure

//rest// returns an empty set () when called on an empty or singleton list, whereas //next// returns //nil//. In clojure, the empty set evaluates as true in a boolean context and //nil// evaluates as false.

# cons ++ cons

clojure

Clojure does not implement a list as a linked list of cons cells. The second argument to //cons// must be a list.

# cond ++ cond

# lambda ++ lambda

clojure:

code (#(+ %1 %2) 1 2) /code

# label ++ label

# apply ++ apply

# arithmetic-logic-note + [#arithmetic-logic Arithmetic and Logic]

integers

Common Lisp and Racket have arbitrary-precision integers and use them by default.

Racket provides the {{fixnum}} library for access to hardware integers:

code (require racket/fixnum)

(fx+ 3 7) /code

Operations on Racket fixnums cause an error when they overflow.

rationals and floats

Common Lisp and Racket have arbitrary-precision rationals. Racket uses them in a number of cases when Common Lisp uses hardware floats:

code 3.14 3e10 (exp 1) /code

Racket provides the {{flonum}} library for access to hardware floats:

code (require racket/flonum)

(fl* 3.1 -7.2) /code

complex numbers

Both the real and imaginary part of a Common Lisp complex number will have the same type, but the type can be integer, rational, or float.

# true-false-note ++ [#true-false true and false]

Literals for true and false.

# falsehoods-note ++ [#falsehoods falsehoods]

Values which evaluate to false in a boolean context.

racket

{{null}} and the empty list {{’{} do not evaluate as false in a boolean context.

# logical-op-note ++ [#logical-op logical operators]

The logical operators.

# relational-op-note ++ [#relational-op relational operators]

Relational operators for performing comparisons.

# min-max-note ++ [#min-max min and max]

Functions for returning the least and greatest of the arguments.

# num-predicates-note ++ [#num-predicates numeric predicates]

A selection of numeric predicates.

//realp// and //real?// are true of all numbers which have a zero imaginary component. //floatp// and //inexact?// are true if the number is being stored in a floating point representation.

racket:

The following all evaluate as #t:

code (rational? 1.1) (rational? (sqrt 2)) (rational? pi) /code

# closure-of-integers ++ closure of integers under division

The number system that containing the potential results of integer division. In mathematics, the closure of integers under division is the rationals, and this is true for common lisp, scheme, and clojure as well.

Emacs lisp performs integer division (i.e. computes the quotient), so the closure of the integers under division is the integers.

# arith-op-note ++ [#arith-op arithmetic operators]

In Lisp, + and * take zero or more arguments and - and / take one or more arguments. With zero arguments + and * return the additive and multiplicative identities 0 and 1. With one argument + and * return the argument and - and / return the additive and multiplicative inverses: i.e. the negation and the reciprocal. When evaluating 3 or more arguments - and / are computed from left to right: i.e. (- 3 4 5) is computed as (- (- 3 4) 5).

clojure:

//Math.pow// returns a double.

emacs:

Unary division (i.e. computing the reciprocal) generates a wrong number of arguments error.

# transcendental-func-note ++ [#transcendental-func transcendental functions]

# float-truncation-note ++ [#float-truncation float truncation]

For rounding, floor, and ceiling, the return value is integer if the argument is rational and floating point if the argument is floating point, unless otherwise noted.

racket:

//inexact->exact// can be used to convert a float returned by //round//, //ceiling//, or //floor// to an integer.

clojure:

//Math/round// always returns an integer and throws and error if called on a rational. //Math/floor// and //Math/ceil// can be called on a rational, but always return a float.

emacs:

//round//, //ceiling//, and //floor// return integers. //fround//, //fceiling//, and //ffloor// return floats.

# quotient-remainder ++ quotient and remainder

# sqrt-negative-two ++ (sqrt -2)

The value of //(sqrt -2)//. Common lisp and Scheme support complex numbers. Clojure and Emacs Lisp do not.

# integer-rational-complex-decomposition ++ decomposition of integer, rational, complex

For absolute value, the type of the return value is the same of the type of the argument.

racket:

The //scheme/math// library must be loaded to use //sgn//.

clojure:

//Math/signum// only operates on a float and returns a float

# random-num-note ++ [#random-num random number]

How to generate a random integer, and a random float in a uniform and a normal distribution.

# bit-op-note ++ [#bit-op bit operators]

racket:

The bitwise operators implemented by Gambit and Racket are specified in the withdrawn standard [http://srfi.schemers.org/srfi-33/ SRFI 33].

emacs:

Also has //ash//, which gives a different value when both arguments are negative.

# strings-note + [#strings Strings]

# character-literal ++ character literals

The syntax for character literals. The first literal uses the letter “a” as an example of how to write a literal for all ASCII printing characters.

common lisp:

Characters are of type standard-char. The predicate is //characterp//.

racket:

The predicate is //char?//.

clojure:

Characters are of type java.lang.Character.

emacs:

Characters are of type integer and can be manipulated by arithmetic operators. //characterp// and //integerp// are synonyms.

# string-literal ++ string literal

The syntax for a string literal.

# string-escapes ++ string escapes

A list of escape sequences that can be used in string literals.

emacs lisp:

The \x escape sequence is followed by one to six hex digits. Because a variable number of hex digits can be used, it may be necessary to indicate the end of the sequence with a backslash and a space, e.g. the following string literal is “λ123”:

code “\x3bb\ 123” /code

# string-char ++ character access

How to get the character at a given position in a string.

# find-substring ++ find substring

Find the location of a substring in a string.

# extract-substring ++ extract substring

# string-length ++ length

# string-constructors ++ constructors

# string-comparison ++ comparison

common lisp:

Here is the complete list of string comparison functions:

code string= string< string> string<= string>= string/= /code

There are also case insensitive versions of the above functions:

code string-equal string-lessp string-greaterp string-not-greaterp string-not-lessp string-not-equal /code

racket:

Case sensitive string comparison:

code string<=? string<? string=? string>=? string>? /code

Case insensitive string comparison:

code string-ci<=? string-ci<? string-ci=? string-ci>=? string-ci>? /code

emacs lisp:

Emacs has only these string comparison functions, all of which are case sensitive:

code string= string-equal string< string-lessp /code

//string=// and //string-equal// are synonyms, as are //string<// and //string-lessp//.

# string-case ++ case

# string-trim ++ trim

emacs:

An implementation of {{trim}}:

code (defun trim (s) (let ((s1 (replace-regexp-in-string “[ \t]$” ““ s))) (replace-regexp-in-string “^[ \t]” ““ s1))) /code

# number-string ++ convert from string, to string

How to convert strings to numbers, and numbers to strings.

common lisp:

//read-from-string// invokes the reader, so the return value is not guaranteed to be a floating point number.

Here is a //parse-float// function which will convert all real numeric types to floats and raise a simple error if another condition is encountered.

code (defun parse-float (s) (let ((readval (handler-case (read-from-string s) (sb-int:simple-reader-error nil) (end-of-file nil)))) (cond ((realp readval ) (+ readval 0.0)) (t (error (concatenate ‘string “not a float: “ s)))))) /code

# string-concat ++ concat

# string-split ++ split

# string-join ++ join

# format ++ format

# regexes-note + [#regexes Regular Expressions]

# regular-expressions ++ regular expressions

common lisp

http://weitz.de/cl-ppcre/

emacs lisp

//string-match// returns the first index of the first matching substring, or nil.

The following code moves the point to next position following the point that matches the argument, and returns the index of the that position.

code (re-search-forward “hello”) /code

# regex-substitution ++ regex substitution

# regex-special-chars ++ regex special characters

# dates-time-note + [#dates-time Dates and Time]

# current-datetime-note ++ [#current-datetime current datetime]

# current-unix-epoch-note ++ [#current-unix-epoch current unix epoch]

# broken-down-datetime-to-unix-epoch-note ++ [#broken-down-datetime-to-unix-epoch unix epoch to broken-down datetime]

# unix-epoch-to-broken-down-datetime-note ++ [#unix-epoch-to-broken-down-datetime broken-down datetime to unix epoch]

# fmt-datetime-note ++ [#fmt-datetime format datetime]

# parse-datetime-note ++ [#parse-datetime parse datetime]

# date-parts-note ++ [#date-parts date parts]

# time-parts-note ++ [#time-parts time parts]

# build-datetime-note ++ [#build-datetime build broken-down datetime]

# lists-note + [#lists Lists]

# list-literal ++ list literal

# pair-literal ++ pair literal

# car-nil ++ (car ‘())

# cdr-nil ++ (cdr ‘())

# eval-nil ++ (eval ‘())

A practical advantage of having //(eval ‘())// be equal to ‘() is that the empty list doesn’t have to be quoted.

# list-functions ++ list functions

# nth ++ nth

//nth// and //list-ref// count from zero. //nth// returns //nil// if the index is too large. //list-ref// throws an error.

# list-element-index ++ index of list element

How to get the index of a list element. The first element of a list has an index of zero.

# last-butlast ++ last butlast

In clojure, //last// and //butlast// are analogs of //first// and //rest// which operate at the end of a list. If X is a list, then the following code pairs are identities:

code (last X) (first (reverse X))

(butlast X) (reverse (rest (reverse X))) /code

The analogy breaks down in Common Lisp because //last// returns a list with a single element.

# set-car-cdr ++ set-car set-cdr

common lisp:

The following code pairs perform the same operation on the list:

code (setf (car l) 3) (rplaca l 3)

(setf (cdr l) ‘(4 5 6)) (rplacd l ‘(4 5 6)) /code

However, they are not identical because //rplaca// and //rplacd// return the modified list instead of their 2nd argument.

racket:

Racket provides a separate interpreter //plt-r5rs// for an R5RS compliant version of Scheme. Also, the language can be set to R5RS within DrRacket.

emacs lisp:

Also has //setf//.

# sort ++ sort

# assoc ++ assoc

clojure

In Clojure, //assoc// returns a new association with the specified values replaced:

code (def numbers {1 :one 2 :two 3 :three 4 :four}) (def jumble (assoc numbers 1 :uno 3 :drei 4 :quatre)) /code

# getf ++ getf

racket:

How to implement //getf// in Scheme:

code (define (getf lst key (default null)) (cond ((null? lst) default) ((null? (cdr lst)) default) ((eq? (car lst) key) (cadr lst)) (else (getf (cddr lst) key default)))) /code

# map ++ map

common lisp

The lambda can accept multiple arguments:

code (mapcar ‘+ ‘(1 2 3) ‘(4 5 6)) /code

racket

code (map + ‘(1 2 3) ‘(4 5 6)) /code

clojure

code (map + ‘(1 2 3) ‘(4 5 6)) /code

emacs lisp

//mapcar// does not accept multiple argument lambdas

# filter ++ filter

common lisp

Also the negative version:

code (remove-if (lambda (x) (> x 2)) ‘(1 2 3)) /code

clojure

Also the negative version:

code (remove #(> % 2) ‘(1 2 3)) /code

emacs lisp

Also has negative version:

code (remove-if (λ (x) (> x 2)) ‘(1 2 3)) /code

# reduce ++ reduce (left fold)

# right-fold ++ right fold

clojure:

How to define {{foldr}}:

code (defn foldr f init list) /code

# sublis ++ sublis

How to apply the mapping defined by an associative list to a recursive list.

++ dolist

# take ++ take

Here is how to define //take// for common lisp or emacs lisp:

code (defun take (n l) (cond ((< n 0) (error “index negative”)) ((= n 0) ()) ((null l) (error “index too large”)) (t (cons (car l) (take (- n 1) (cdr l)))))) /code

# drop ++ drop

# push-pop ++ push and pop

racket:

Here is an implementation of //push// and //pop// in Racket using boxes:

code (define (push x a-list) (set-box! a-list (cons x (unbox a-list))))

(define (pop a-list) (let ((result (first (unbox a-list)))) (set-box! a-list (rest (unbox a-list))) result)) /code

clojure:

Note the in clojure, //pop// only returns the first element; the original list is left unmodified.

# fixed-length-arrays-note + [#fixed-length-arrays Fixed-Length Arrays]

# vector-literal ++ vector literal

racket

//#(1 2 3)// creates an immutable vect. //(vector 1 2 3)// creates a mutable vector.

# vector-access ++ vector access

# set-vector-element ++ set vector element

racket

//vector-set!// throws an error if called on an immutable vector.

# vector-to-list ++ vector to list

# list-to-vector ++ list to vector

# abstract-sequence ++ abstract sequence

Lists and vectors support the same operations; the only difference is the speed at which the operations can be performed. It is a convenience for the developer if functions that perform the operations have the same name; i.e. if lists and vectors are members of an abstract sequence type. Clojure has gone furthest in this direction, making all the customary list functions work on vectors as well. In common lisp and emacs lisp, some of the list functions also work on vectors, and some don’t. In Scheme none of the list functions work on vectors.

# sequence-data-types ++ sequence data types

The containers that respond to sequence functions.

# sequence-predicate ++ sequence predicate

# sequence-functions ++ list functions usable on sequences

# make-array ++ make-array

In Lisp terminology, both arrays and vectors refer to collections which are of fixed size; vectors are arrays with rank 1. Only common lisp supports arrays with rank greater than 1.

# array-access ++ array access

# set-array-element ++ set array element

# array-dimensions ++ array dimensions

//array-rank// returns the number of indices required to specify an element in the array. //array-dimensions// returns the size of the array; the number of cells is the product of the elements of the list.

# range ++ range

# list-comprehension ++ list comprehension # dictionaries-note + [#dictionaries Dictionaries]

Lisp has a tradition of using lists of pairs for dictionaries. The data structures in this section are implemented using hash tables.

racket:

In addition to hash tables there are a set of functions which work with any dictionary type, which in Racket include hash tables, lists of cons cell pairs, and vectors. When a vector is treated as a dictionary, the value is an element and the key is the integer index of the element.

clojure:

There are three dictionary types which can be used with the functions described in this section:

||~ constructor||~ type|| ||(hash-map “t” 1 “f” 0)||clojure.lang.PersistentHashMap|| ||(array-map “t” 1 “f” 0)||clojure.lang.PersistentArrayMap|| ||(zipmap ‘(“t” “f”) ‘(1 0))||clojure.lang.PersistentArrayMap|| ||(sorted-map “t” 1 “f” 0)||clojure.lang.PersistentTreeMap|| ||(sorted-map-by #(< %1 %2) “t” 1 “f” 0)||clojure.lang.PersistentTreeMap||

# dict-literal-note + [#dict-literal literal]

The syntax for a dictionary literal.

# dict-ctor-note + [#dict-ctor constructor]

The constructor for a dictionary.

racket:

The constructors use {{equal?}} to test for equality of the two keys.

There are also constructors which use {{eq?}} or {{eqv?}} to test keys: {{hasheq}}, {{hasheqv}}, {{make-immutable-hasheq}}, {{make-immutable-hasheqv}}.

# dict-pred-note + [#dict-pred predicate]

How to test whether a value is a dictionary.

# dict-size-note + [#dict-size size]

How to get the number of keys stored in the dictionary.

# dict-lookup-note + [#dict-lookup lookup]

How to look up the value associated with a key.

# dict-update-note + [#dict-update update]

How to insert a key-value pair or replace the value stored with an existing key.

# dict-missing-key-note + [#dict-missing-key missing key behavior]

What happens when a lookup is performed on a key not in the dictionary.

racket:

How to handle the error and return a null when the key is not found:

code (with-handlers ((exn:fail? (lambda (e) null))) (get h “goodbye”)) /code

# dict-is-key-present-note + [#dict-is-key-present is key present]

How to check whether a key exists in a dictionary.

# dict-del-note + [#dict-del delete]

How to remove a key and its associated value from a dictionary.

# dict-merge-note + [#dict-merge merge]

How to merge two dictionaries.

# dict-invert-note + [#dict-invert invert]

How to turn a dictionary into its inverse. If a key ‘foo’ is mapped to value ‘bar’ by a dictionary, then its inverse will map the key ‘bar’ to the value ‘foo’.

If multiple keys are mapped to the same value in the original dictionary, some of the keys will be discarded in the inverse.

# dict-iter-note + [#dict-iter iterate]

How to iterate over the key-value pairs in a dictionary.

# dict-key-val-lists-note + [#dict-key-val-lists keys and values as lists]

How to get the keys or the values in a dictionary as lists.

# user-defined-types-note + [#user-defined-types User-Defined Types]

# defstruct ++ defstruct

# struct ++ struct

# struct-getter ++ struct getter

# struct-setter ++ struct setter

# struct-predicate ++ struct predicate

# functions-note + [#functions Functions]

# let# let-star ++ let, let*

Traditionally {{let}} performs its assignments in parallel and {{let*}} serially.

clojure

In Clojure, //let// and //let*// are synonyms and both perform serial assignment.

emacs

Note that {{let}} uses dynamic scope. Use {{lexical-let}} for lexical scope:

code ELISP> (let ((x 3)) (defun get-x () x)) get-x ELISP> (get-x) *** Eval error *** Symbol’s value as variable is void: x ELISP> (let ((x 4)) (get-x)) 4 ELISP> (lexical-let ((x 3)) (defun get-x-2 () x)) get-x-2 ELISP> (get-x-2) 3 ELISP> (lexical-let ((x 4)) (get-x-2)) 3 /code

# define-function ++ define function

# optional-argument ++ optional argument

# variable-arguments ++ variable number of arguments

# default-value ++ default value

# named-parameter ++ named parameter

common lisp:

In common lisp, named parameters are optional. Named values can be assigned default values:

code (defun logarithm (&key number (base 10)) (/ (log number) (log base))) /code

If a named parameter is not provided at invocation and has not been assigned a default value, then it is set to //nil//.

racket:

[http://rosettacode.org/wiki/Named_parameters#Scheme How to Implement Named Parameters in Scheme]

emacs lisp:

In emacs lisp named parameters are mandatory. A runtime error results in they are not provided when the function is invoked.

# tail-call ++ tail call optimization

common lisp:

The ANSI Common Lisp specification does not require an implementation to perform tail call optimization.

# docstring-note ++ [#docstring get docstring]

How to get the documentation string for a function.

common lisp:

{{describe}} returns the documentation string with additional information such as the function signature. To get just the documentation string use this:

code (documentation #’mapcar ‘function) /code

# define-docstring-note ++ [#define-docstring define function with docstring]

How to define a function that has a documentation string.

# search-doc-note ++ [#search-doc apropos and documentation search]

How to search definitions and documentation.

Apropos takes a pattern and returns all defined symbol names which match the pattern.

clojure:

{{apropos}} returns matching symbol names as a list.

{{find-doc}} searches all documentation strings and writes any which match to standard out.

Both {{apropos}} and {{find-doc}} can take a string or a regular expression as an argument.

emacs lisp:

{{apropos}} displays the documentation for matching definitions in the {{Apropos}} buffer. The argument is a string but will be treated as a regular expression.

# execution-control-note + [#execution-control Execution Control]

# progn ++ progn

//progn// and its equivalents in other dialects returns the value of the last expression. Common Lisp and Emacs Lisp also have //prog1// and //prog2// for returning the value of the 1st or 2nd expression.

# loop ++ loop

# do ++ do

# dotimes ++ dotimes

# if ++ if

# when ++ when

# exceptions-note + [#exceptions Exceptions]

# error ++ error

# handle-error ++ handle error

racket:

Calling //error// raises an exception of type exn:fail

emacs:

In the example:

code (condition-case nil (error “failed”) (error (message “caught error”) nil)) /code

the 2nd argument to //condition-case// is the code which might raise an error, and the 3rd argument is the error handler. The error handler starts with condition to be caught. The last //nil// is the return value of the entire //condition-case// expression.

An error cannot be handled by catch. An uncaught throw will generate an error, which can be handled by a condition-case error handler.

# define-exception ++ define exception

How to define a custom exception with a payload.

common lisp:

The :report clause is not necessary. If defined it will be displayed if the exception is handled by the lisp debugger.

# throw-exception ++ throw exception

emacs:

The 1st argument of an emacs //throw// expression identifies the type of exception, and the 2nd argument will be the return value of the //catch// expression that catches the exception.

# catch-exception ++ catch exception

emacs

The following //catch// expression will return //nil//:

code (catch ‘failed (throw ‘failed nil) t) /code

# restart-case ++ restart case

# invoke-restart ++ invoke restart

# finally-clause ++ finally clause

racket:

clojure:

Here is an optional technique for making sure that a file handle is closed:

code (with-open #^PrintWriter w (writer f)) /code

# lazy-evaluation ++ lazy evaluation

# continuations ++ continuations

# streams-note + [#streams Streams]

# std-file-handles-note ++ [#std-file-handles standard file handles]

# eof-note ++ [#eof end-of-file behavior]

# read-stdin-note ++ [#read-stdin read line from stdin]

# chomp-note ++ [#chomp chomp]

# println-note ++ [#println write line to stdout]

# format-stdout-note ++ [#format-stdout write formatted string to stdout]

racket

//printf// prints to stdout. //format// returns a string.

emacs lisp

The //format// statement returns the generated string. When used for i/o, it prints in the emacs minibuffer.

# open-file-note ++ [#open-file open file for reading]

# open-file-write-note ++ [#open-file-write open file for writing]

# open-file-append-note ++ [#open-file-append open file for appending]

# close-file-note ++ [#close-file close file]

# close-file-implicitly-note ++ [#close-file-implicitly close file implicitly]

# read-line-note ++ [#read-line read line]

# iterate-file-note ++ [#iterate-file iterate over file by line]

# read-file-array-note ++ [#read-file-array read file into array of strings]

# read-file-str-note ++ [#read-file-str read file into string]

# write-str-note ++ [#write-str write string]

# write-line-note ++ [#write-line write line]

# flush-file-note ++ [#flush-file flush filehandle]

# emacs-buffers-note + [#emacs-buffers Emacs Buffers]

# files-note + [#files Files]

# file-test-note ++ [#file-test file test, regular file test]

# file-size-note ++ [#file-size file size]

# file-readable-writable-executable-note ++ [#file-readable-writable-executable is file readable, writable, executable]

# chmod-note ++ [#chmod set file permissions]

# cp-rm-mv-note ++ [#cp-rm-mv copy file, remove file, rename file]

# symlink-note ++ [#symlink create symlink, symlink test, get target]

# tmp-file-note ++ [#tmp-file temporary file]

# in-memory-file-note ++ [#in-memory-file in memory file]

# directories-note + [#directories Directories]

# build-pathname-note ++ [#build-pathname build pathname]

How to build a file pathname from components.

# dirname-basename-note ++ [#dirname-basename dirname and basename]

How to extract the directory portion of a pathname; how to extract the non-directory portion.

# abs-pathname-note ++ [#abs-pathname absolute pathname]

How to get the get the absolute pathname for a pathname. If the pathname is relative the current working directory will be appended.

# iterate-dir-note ++ [#iterate-dir iterate over a directory by file]

How to iterate over the files in a directory.

# mkdir-note ++ [#mkdir make directory]

How to create a directory, including any parents directories specified in the path.

# recursive-cp-note ++ [#recursive-cp recursive copy]

How to copy a directory and its contents.

# rmdir-note ++ [#rmdir remove empty directory]

How to remove an empty directory.

# rm-rf-note ++ [#rm-rf remove directory and its contents]

How to remove a directory and its contents.

# dir-test-note ++ [#dir-test directory test]

How to test whether a directory exists.

# processes-environment-note + [#processes-environment Processes and Environment]

# external-command ++ external command

# command-line-arguments ++ command line arguments

emacs

The global variables //command-line-args// and //argv// are set when emacs is run in shebang mode: i.e. with the –script option. //command-line-args// contains the pathname used to invoke emacs, as well as any options processed by emacs at startup, in addition to any additional arguments. //argv// only contains the additional arguments.

# environment-variables ++ environment variables

# libraries-namespaces-note + [#libraries-namespaces Libraries and Namespaces]

# load-file ++ loading a file

How to load a file and evaluate the top level expressions.

common lisp

Does not display the result of any evaluations.

racket

Displays the result of the last evaluation.

# load-library ++ loading a library

# objects-note + [#objects Objects]

# defclass ++ define class

# make-instance ++ make instance

# read-attribute ++ read attribute

# write-attribute ++ write attribute

# defmethod ++ define method

# invoke-method ++ invoke method

# define-subclass ++ define subclass

# universal-superclass ++ universal superclass

# multiple-inheritance ++ multiple inheritance

# lisp-macros-note + [#lisp-macros Lisp Macros]

# backquote-comma ++ backquote and comma

# defmacro ++ defmacro

# defmacro-backquote ++ defmacro-backquote

# macro-predicate ++ macro predicate

# macroexpand ++ macroexpand

//macroexpand// recursively expands a sexp until the head is no longer a macro. It does not expand arguments that are macros.

common lisp

Common lisp also has //macroexpand-1//, which will non-recursively expand a macro once. The head of the expansion may thus be a macro.

clojure

Clojure also has //macroexpand-1//. See above for an example of use.

emacs lisp

Emacs has //macroexpand-all//, which will recursively expand a sexp until head and arguments are free of macros.

# splice-quote ++ splice quote

# recursive-macro ++ recursive macro

# hygienic ++ hygienic

Does the language have macros whose expansions are guaranteed not to introduce name collisions.

# local-values ++ local values

# reflection-note + [#reflection Reflection]

# type-of ++ type-of

How to get the data type of the entity referred to by a symbol.

# java-interop-note + [#java-interop Java Interoperation]

# version-used-jvm ++ version used on jvm

# java-extra-libraries ++ extra libraries used

racket:

The srfi-1 library brings in a common list functions which Kawa does not make available by default. See [http://srfi.schemers.org/srfi-1/srfi-1.html SRFI].

# java-new ++ new

# java-method ++ method

# java-class-method ++ class method

# java-chain ++ chain

# java-import ++ import

# java-to-array ++ to java array

# common-lisp + [#top Common Lisp]

[http://www.lispworks.com/documentation/HyperSpec/Front/ ANSI Specification] [http://www.sbcl.org/manual/ SBCL User Manual] [http://www.quicklisp.org/beta/ Quicklisp]

For a package manager we use Quicklisp. Here is how to install it and use it to load the {{cl-ppcre}} library:

code $ curl -O http://beta.quicklisp.org/quicklisp.lisp $ sbcl * (load “quicklisp.lisp”) * (quicklisp-quickstart:install) * (ql:quickload “cl-ppcre”) * (cl-ppcre:all-matches “foo” “foo bar”) /code

Quicklisp creates a {{quicklisp}} directory in the user’s home directory. Once quicklisp is downloaded and installed, it can be used like this:

code $ sbcl * (load “~/quicklisp/setup.lisp”) * (ql:quickload “cl-ppcre”) * (cl-ppcre:all-matches “foo” “foo bar”) /code

One can ensure that Quicklisp is automatically loaded at startup by putting the load command into the {{.sbclrc}} file:

code $ cat ~/.sbclrc (load “~/quicklisp/setup.lisp”) /code

# racket + [#top Racket]

[http://docs.racket-lang.org/guide/index.html Guide: Racket] [http://docs.racket-lang.org/reference/index.html Reference: Racket] [http://planet.racket-lang.org/ PLaneT: Racket Packages]

Racket ships with a large number of libraries in the {{collects}} directory of the installation which can be loaded with the {{require}} command, which takes a raw symbol which is the relative pathname from the {{collects}} directory to the file, not including the {{.rkt}} suffix. The Racket 5.1 distribution includes 50 SRFI libraries.

Racket also has a built in package management system. Browse the [http://planet.racket-lang.org/ list of available packages]. To install a package, click through to the detail page for the package and get the {{require}} string to load it. If the {{require}} string is executed by Racket, the library will be downloaded somewhere in the user’s home directory. When I ran this on my Mac

code $ racket

(require (planet “spgsql.rkt” (“schematics” “spgsql.plt” 2 3))) /code

the files for the PostgreSQL database bindings were installed in {{~/Library/Racket}}.

# clojure + [#top Clojure]

[http://clojure.org/Reference Clojure Reference] [http://clojure.org/cheatsheet Clojure Cheat Sheet]

++ Calling Java

Here are the basics of calling Java code:

code (def rnd (new java.util.Random)) ; create Java object (. rnd nextFloat) ; invoke method on object (. rnd nextInt 10) ; invoke method with argument (. Math PI) ; static member (import ‘(java.util Random)) ; import /code

Clojure automatically imports everything in java.lang.

There are shortcuts for the above syntax:

code (Random.) (new Random)

Math/PI (. Math PI)

(.nextInt rnd) (. rnd nextInt) /code

Because they are primitive types and not objects, Clojure provides functions specific to Java arrays:

code (make-array CLASS LEN) (make-array CLASS DIM & DIMS) (aset ARY IDX VAL) (aset ARY IDXDIM1 IDXDIM2 … VAL) (aget ARY IDX) (aget ARY IDXDIM1 IDXDIM2 …) (alength JARY) (to-array SEQ) (into-array TYPE SEQ) (amap ARY I COPY EXPR) (areduce ARY IDX COPY INIT EXPR ) /code

# emacs-lisp + [#top Emacs Lisp]

[http://www.gnu.org/software/emacs/manual/html_mono/emacs.html GNU Emacs Manual] [http://www.gnu.org/software/emacs/manual/html_mono/elisp.html GNU Emacs Lisp Reference Manual]

To get an introduction to Emacs Lisp Programming from within Emacs use

code C-h i m Emacs Lisp Intro /code

Run {{M-x lisp-interaction-mode}} to put Emacs in lisp interaction mode. In lisp interaction mode the command {{C-x e}} will evaluate the s-expression on the current line. {{M-x eval-buffer}} will evaluate the entire buffer.

Use lisp interaction mode to define functions which can be called from Emacs. The following defines a function called {{dired-emacs-lisp}} for browsing the Emacs Lisp directory:

code (defun dired-emacs-lisp () “Open the Emacs Lisp directory in dired.” (interactive) (dired “/Applications/Emacs.app/Contents/Resources/lisp”)) /code

The directory is hard-coded into the function and may be different on your system. Once defined the function can be invoked with {{M-x dired-emacs-lisp}}. Not all Lisp functions can be called in this manner. Those that can are called //commands//. The body of a command has an optional documentation string, followed by a call to {{interactive}}, followed by the code which executes when the command is invoked. The documentation string can be accessed from Emacs by running {{M-x describe-function}} and entering the name of the function when prompted.

The call to {{interactive}} is what makes a Lisp function a command. It can takes optional arguments. Use {{M-x describe-function}} on {{interactive}} to see a description of these arguments.

To bind the command to the key {{C-c l}} run the following in Lisp interaction mode:

code (global-set-key “\C-cl” ‘dired-emacs-lisp) /code

If it is desired to have the above command and key binding always available when Emacs starts up, put them in {{~/.emacs.d/init.el}}.