CSCI 330 Lisp Syntax Reference
 ; to define as a script
#! /usr/bin/gcl -f

; 'x or (quote x) to prevent evaluation

; global variables and constants, setf
(defvar x 3)
(defconstant y 0)
(setf x y)

; func with local vars, functions,
;    optional and var number of params,
;    and returning a lambda dispatch function
(defun f (x y &optional (z 0) &rest r)
   (let* ((a 1) (b 2))
      (labels ( (g (i j) ... body of g ...)
                (h (k l) ... body of h ...) )
      ... initialization for f ...
      (lambda (cmd &optional (arg1 nil) (arg2 nil))
         ... body of dispatcher, e.g.:
         (cond
             ((equal cmd 'whatever) (g a b))
              ... etc ...
              )))))

; function with mix of regular and keyword params, and
;    using a dynamically scoped variable from ancestor
(defun f (x &key y z)
   (declare (special w))
   ... body of f ...)

; sample call to f
(f 10 :z 3 :y 2)

; formats for output to stdout or to string
(format t   "x is ~A~%" x)
(format nil "x is ~A~%" x)
(force-output) ; clear output buffer

; read a lisp term, an entire line, or a char
(read) (read-line) (read-char)
(read-from-string str)
(unread-char c) ; put back in buffer
(clear-input) ; clear input buffer

; common conditionals (cond shown earlier)
(if (< x y) expr_if_true  expr_if_false)
(when (< x y) ... things to do if true ...)
(unless (< x y) ... things to do if false ...)
(case expr
   (val1  ...what to do if expr==val1...)
   (val2  ...what to do if expr==val2...)
   (otherwise ...what to do otherwise...))
(typecase expr
   (string  ...what to do if expr is a string...)
   (integer ...what to do if expr is an integer..)
   (t ...what to do otherwise...))
; math functions and literals
; literals:  3.55   3/2   17
; comparisons:  <  <=  >  >=  =  /=
; unary funcs: + - sin cos tan sqrt
;    incf decf abs ceiling floor
; other funcs: + - / * mod min max exp log gcd lcm

; char functions and literals
(setf x #\q)  ; char literal q
; comparisons: char= char/= char< etc
(code-char 63) (char-code c) ; convert from/to ascii
(char-upcase c) (char-downcase c) ; convert case
; special chars: #\Newline #\Backspace #\Tab

; logic functions
; t is true, nil or '() are false
(and a b c) (not x) (or a b c)

; bitwise 2's complement functions
; logic: logand, logior, lognot, logxor, etc
; shift: (ash x n) (ash x -n) shifts left/right n bits

; seq functions (can be used with lists, arrays, etc)
(make-sequence 'list 3 :initial-element 0)
(length s) (elt s pos) (count e s) (position e s)
(substitute newE oldE s) (copy-seq s) (remove e s)
(concatenate 'string s1 s2) ; specifies type of sequence

; list functions and literals
(cons e L) (car L) (cdr L) ; combos to 4, eg. cdadar
(length L) (nth n L) (append L1 L2) (member e L)
(reverse L) (null L) (copy-list L) (last L) (butlast L)
(pop L) (push e L) (list 1 2 3 4)

; hash functions
(make-hash-table) (gethash key H) (setf (gethash k H) val)
(remhash key H) (hash-table-count H)
(maphash f H)  ; apply f to H's key/value pairs
(loop for k being the hash-keys of H do
   ... do stuff with key k ...)
; can use similar loop for hash-values

; array functions
(make-array '(3 4) :initial-element 0)
(aref arr i j) (array-dimensions arr)
(setf (aref arr i j) value)

; vector functions
(vector 10 20 30) (svref vec pos)
(setf (svref vec pos) val)

; string functions
; comparisons: string=, string/=, string< etc
(count str c) (char str pos)
(string-upcase str) (string-downcase str)
(substitute oldC newC str)
(parse-integer "1234")

; struct functions
(defstruct S field1 field2 field3)
; functions built by defstruct
   (make-S) (S-p x) (copy-S x)
   (S-field1 x) (S-field2 x) etc
(setf (S-field1 x) val)

; symbol functions and literals
(symbol-name sym) (intern "sym")
(makunbound sym) (fmakunbound sym)
(symbol-plist sym) (get sym prop)
(setf (get sym prop) val) (remprop sym prop)

; equality checking, least strict to most
equalp, =, eq, equal

; typechecking functions
numberp realp floatp integerp fixnump stringp
characterp listp sequencep hash-table-p arrayp
vectorp symbolp boundp fboundp
(typeof item) (typep item type) (coerce item type)

; higher order functions and calls
(funcall f x y z) (apply f '(x y z)) (eval '(f x y z))
(map 'list '* '(10 20) '(1 2)) ; (10 40)
(mapcar '- '(1 2 3)) ; (-1 -2 -3)
(maplist 'length '(10 20 30)) ; (3 2 1)
(reduce 'exp '(3 4 5)) computes (3^4)^5

; macros
(defmacro m (x L &rest r)
   (let ((s (gensym)))
      `... body of macro ...
       ,L  ; to embed L as a list
       ,@L ; to embed contents of L
       ,s  ; to use the generated symbol
      ))

; do, dolist, dotimes
(dolist (x L) ...do stuff with x...)
(dotimes (x numTimes (+ x 1)) ...do stuff with x...)
(do ( (x 0 (+ x 1)) (y 10 (- y 1)) ) ; local var, init, update
    ( (> x y) ; stopping condition
      ...stuff to do after stopping... )
    ...loop body...)

; returning and capturing multiple values
(values val1 val2 val3)
(nth-value n (function call))
(multiple-bind (a b c) (function call)
   ... do stuff with a b c ...)

; nested blocks, return from
(block 'OuterBlock
   ... actions ...
   (block 'InnerBlock
      ... actions ...
      (if (expr) return-from 'OuterBlock)
      ... actions ...))

CSCI 330 C/C++ Syntax Reference
// C examples

// comma operator example:
// increment y then print hi then return 17
x = (y++, printf("hi\n"), 17);

// ternary operator example:
// if (x > y) return x, else return y
answer = (x > y) ? x : y;

// sizeof, align: apply to any data type
answer = sizeof (int);
answer = alignof(int);

// labels gotos (here as a while loop):
TOP: sum += x;
     x++;
     if (x < y) goto TOP;

// && to lookup address associated with label:
     addr = &&TOP;

// function pointers int foo(float x, char c); // prototype for a func int (*f)(float, char); // a function ptr variable f = foo; // set var f to point at function foo y = (*f)(3.1, 'q'); // call foo using f // prototype for func accepting func ptr as param void useAfunc(int (*fptr)(float,char)); // prototype for func that accepts two ints as params // and returns a ptr to a function like foo int (*returnsAfunc(int x, int y))(float, char); // typedef for a function pointer like f typedef int (*fPtr)(float, char); fPtr f2 = foo;
// C pre-processor examples

// basic substitution and some predefined macros
#define SIZE 99
// __FILE__, __LINE__, __DATE__, __TIME__, __VERSION__

// macro-style, using \ for line continuation
//    and using ## to build a local varname
#define swap(t, x, y)  { \
    t x##y = x; x = y; y = x##y; }

// conditionals
#define DEBUG_LEVEL 1
#if DEBUG_LEVEL == 0
    // include this code
#elif DEBUG_LEVEL == 1
    // include this code
#else
    // include this code
#endif

// wrappers (header-file style)
#ifndef SOMENAME
#define SOMENAME
   // use this code
#endif

// variadic functions using varargs, uses stdarg.h
// - the first arg passed must be the number of remaining args
long f(int numArgs, ...)
{
   va_list argList;
   va_start(argList, numArgs);
   for (int i = 0; i < numArgs; i++) {
       long current = va_arg(argList, long);
       // ... use current for whatever ...
   }
   va_end(argList);
   return whateverTheResultIs;
}
// C++ examples

// templated functions, instantiation
<template class T1, class T2, class T3>
T1 f(T2 x, T3 y)
{
   ... do whatever with x and y ...
}

// explicit instantiation for "double f(float x, int y)"
template double f<double, float, int>(double f(float x, int y);


// variadic functions using templates template <typename T> T sum(T x) { // the 1-param case return x; } template <typename T, typename... Args> T sum(T front, Args... args) { // the general case return front + sum(args...); }
// smart pointers, use library tr1/memory std::tr1::shared_ptr<SomeClass> ptr1, ptr2; ptr1.reset(new SomeClass); // set the ptr ptr2 = ptr1; // copy to a second ptr ptr1.reset(); // clear a ptr std::tr1::weak_ptr<SomeClass> wptr; wptr = ptr2; if (std::tr1::shared_ptr<SomeClass> tmp = wptr.lock()) { tmp.someMethod(); // access the class }