Common Lisp. Blake McBride

Similar documents
Common LISP Tutorial 1 (Basic)

CSCI337 Organisation of Programming Languages LISP

Lecture Notes on Lisp A Brief Introduction

CS 480. Lisp J. Kosecka George Mason University. Lisp Slides

Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.

Symbolic Programming. Dr. Zoran Duric () Symbolic Programming 1/ 89 August 28, / 89

LISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits.

Allegro CL Certification Program

Common LISP-Introduction

INF4820. Common Lisp: Closures and Macros

Imperative, OO and Functional Languages A C program is

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Introduction to Lisp

Copyright (c) 1988, by David Michael Betz All Rights Reserved Permission is granted for unrestricted non-commercial use

Allegro CL Certification Program

Functions, Conditionals & Predicates

A little bit of Lisp

Recursion & Iteration

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. More Common Lisp

CSCI 2210: Programming in Lisp. Progn. Block. CSCI Programming in Lisp; Instructor: Alok Mehta 1. ANSI Common Lisp, Chapters 5-10

Functional programming with Common Lisp

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY,

LISP - QUICK GUIDE LISP - OVERVIEW

Lisp Basic Example Test Questions

CIS4/681 { Articial Intelligence 2 > (insert-sort '( )) ( ) 2 More Complicated Recursion So far everything we have dened requires

Look at the outermost list first, evaluate each of its arguments, and use the results as arguments to the outermost operator.

A Genetic Algorithm Implementation

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE,

Announcements. Today s Menu

CMPUT325 Extensions to Pure Lisp. Extensions to Pure Lisp. Bob Price and Russ Greiner. 5th October 2004

Gene Kim 9/9/2016 CSC 2/444 Lisp Tutorial

Artificial Intelligence Programming

Scheme Quick Reference

Scheme Quick Reference

INF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals

Robot Programming with Lisp

Lecture #2 Kenneth W. Flynn RPI CS

(defmacro while (condition &body body) `(iterate loop () (if,condition (loop)))))

Review of Functional Programming

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 5. LISP: MAKRA, DATOVÁ STRUKTURA ZÁZNAM

1 CLWEB INTRODUCTION 1

Lecture #5 Kenneth W. Flynn RPI CS

Symbolic Computation and Common Lisp

Introduction to ACL2. CS 680 Formal Methods for Computer Verification. Jeremy Johnson Drexel University

Debugging in LISP. trace causes a trace to be printed for a function when it is called

(defun fill-nodes (nodes texts name) (mapcar #'fill-node (replicate-nodes nodes (length texts) name) texts))

Lambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky.

A Quick Introduction to Common Lisp

Documentation for LISP in BASIC

CSE 341 Section Handout #6 Cheat Sheet

XLISP PLUS. Reference Manual. Version 3.0

CSC 533: Programming Languages. Spring 2015

Functional Programming with Common Lisp

Department of Computer and information Science Norwegian University of Science and Technology

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

(defvar *state* nil "The current state: a list of conditions.")

Introduction to Scheme

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 3. LISP: ZÁKLADNÍ FUNKCE, POUŽÍVÁNÍ REKURZE,

Scheme as implemented by Racket

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

CSCE476/876 Fall Homework 3: Programming Assignment Using Emacs and Common Lisp. 1 Exercises (15 Points) 2. 2 Find (6 points) 4

6.034 Artificial Intelligence February 9, 2007 Recitation # 1. (b) Draw the tree structure corresponding to the following list.

Intro. Scheme Basics. scm> 5 5. scm>

Scheme: Strings Scheme: I/O

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

FP Foundations, Scheme

19 Machine Learning in Lisp

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Note that pcall can be implemented using futures. That is, instead of. we can use

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

User-defined Functions. Conditional Expressions in Scheme

CS 314 Principles of Programming Languages

Project 2: Scheme Interpreter

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

Allegro CL Certification Program

15 Unification and Embedded Languages in Lisp

History. Functional Programming. Based on Prof. Gotshalks notes on functionals. FP form. Meaningful Units of Work

LISP - SEQUENCES. The function make-sequence allows you to create a sequence of any type. The syntax for this function is:

Robot Programming with Lisp

Many versions: Franz, Mac, Inter, Common (now the

DSV Library for Lisp

If we have a call. Now consider fastmap, a version of map that uses futures: Now look at the call. That is, instead of

Lisp. Versions of LISP

A Simple Java Code Generator for ACL2 Based on a Deep Embedding of ACL2 in Java

LECTURE 16. Functional Programming

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

Meet the Macro. a quick introduction to Lisp macros. Patrick Stein / TC Lisp Users Group /

Func%onal Programming in Scheme and Lisp

Essentials of Programming Languages Language

Essentials of Programming Languages Language

Algorithms for AI and NLP (INF4820 Lisp & FSAs)

CS 314 Principles of Programming Languages. Lecture 16

INDEX. Symbols & Numbers

Func%onal Programming in Scheme and Lisp

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

CS 842 Ben Cassell University of Waterloo

Chapter 1. Fundamentals of Higher Order Programming

Functional programming techniques

Transcription:

Contents Common Lisp Blake McBride (blake@mcbride.name) 1 Data Types 2 2 Numeric Hierarchy 3 3 Comments 3 4 List Operations 4 5 Evaluation and Quotes 5 6 String Operations 5 7 Predicates 6 8 Math Predicates 6 9 Logical Operators 7 10 Program Control 7 11 Local Variables 8 12 Defining Functions 8 12.1 Lambda Argument Types................................ 8 13 Conditionals 8 14 Numeric Operators 9 15 Iteration 9 16 Displaying 10 17 Format 10 18 Arrays 11 19 Hash Tables 11 20 Structures 11 21 Function References 11 22 Mapping 12 23 Packages & Modules 12 24 Global Variables 13 25 Macros 14 25.1 defmacro.......................................... 14 25.2 Macro Templates..................................... 14 1

1 DATA TYPES 1 Data Types Type Comment Example null null list & false nil boolean true t integer decimal 48 binary #b1011 binary #2r1011 octal #o755 hex #xd5 ratio 2/3 hex #xde/ff float default precision 3.141 short precision 3.141s0 single precision 3.141f0 double precision 3.141d0 long precision 3.141L0 character letter M #\M #\Space #\Newline semi-standard #\Backspace #\Tab #\Linefeed #\Return #\Page symbol case insensitive (upcased) 'symb case sensitive ' symb embedded ( 'sy\(mb in keyword package :symb external symbol in ppp package ppp:symb internal symbol in ppp package ppp::symb string with embedded " "hello\" there" cons list '(hello there) rev. 11/26/16 Page 2 of 14

3 COMMENTS Data Types (continued) Type Comment Example vector #(3 4 hello) (vector 3 4 'hello) bit vector #*1011 array 2 dimensional array #2A((1 2 3) (4 5 6)) (type of obj) returns the type of the object passed 2 Numeric Hierarchy t number real rational integer fixnum (most positive fixnum) bignum ratio float short float single float (4 bytes?) double float (8 bytes?) long float 3 Comments Semi-colon ; introduces a comment. Comments extend from the semi-colon to the end of the line. rev. 11/26/16 Page 3 of 14

4 LIST OPERATIONS 4 List Operations Type Comment Sp D Example Result car first element fast no (car '(A B C)) A (car nil) nil cdr rest of list fast no (cdr '(A B C)) (B C) (cdr nil) nil c????r shorthand for fast no multiple car & cdr s cons add a list node fast no (cons 'A '(B C)) (A B C) list create a list fast no (list 'A 'B 'C) (A B C) append append lists slow no (append '(A B) '(D) '(G H)) (A B D G H) length slow no (length '(A B C)) 3 nth slow no (nth 1 '(A B C)) B (nth 8 '(A B C)) nil rest same as cdr first same as (nth 0 x) second same as (nth 1 x) third same as (nth 2 x) etc. last slow no (last '(A B C)) (C) Given: (setq lst '(A B C)) rplaca replace car cell fast yes (replaca lst 'X) (X B C) rplacd replace cdr cell fast yes (replacd lst 'X) (A. X) Sp = Speed D = Destructive rev. 11/26/16 Page 4 of 14

6 STRING OPERATIONS 5 Evaluation and Quotes Lists are recursively evaluated. The first element of a list is the function and the remainder are arguments to the function. For example: (func arg1 arg2 Quoting stops evaluation, so (quote (abc def ghi)) would not attempt to evaluate abc, def, or ghi. The ' symbol acts as a shorthand for quote, so the following is equivelent to the previous statement. '(abc def ghi) 6 String Operations "This is\" a string" (string "new string") (length str) (concatenate 'string str1 str2) (schar str idx) or (char str idx) or (aref str idx) (setf (aref str idx) #\X) (subseq str start [end]) (search "abc" str) (parse integer str [:start x] [:end y]) (string #\x) rev. 11/26/16 Page 5 of 14

8 MATH PREDICATES 7 Predicates function null symbolp atom consp listp numberp integerp rationalp floatp characterp stringp bit-vector-p eq eql equal equalp Returns NIL, or T for null symbols non-list items list items (excluding NIL) list items (including NIL) all numbers integers rational numbers floating point numbers characters strings bit vectors same object same object, character, or numbers of the same type structurally similar objects, string compare case insensitive string compare, elements of an array 8 Math Predicates These also work if the numbers aren t the same type. Function (numberp n) (zerop n) (plusp n) (minusp n) (oddp n) (evenp n) (integerp n) (= a b) (/= a b) (< a b) (> a b) (<= a b) (>= a b) Description is n a number rev. 11/26/16 Page 6 of 14

10 PROGRAM CONTROL 9 Logical Operators function Example Comment not (not exp) Logical inverse and (and exp1 exp2 Stops evalution on first null expression or (or exp1 exp2 Stops evalution on first non-null expression and and or can be used as conditionals too. For example: (and exp1 exp2 exp3) is the same as (if exp1 (if exp2 exp3)) 10 Program Control (progn exp1 exp2 (prog1 exp1 exp2 (prog2 exp1 exp2 (prog ((var1 val1) ; initialize var1 to val1 var2 ; initialize var2 to nil exp1 lbl exp2 (go lbl) ; branch to label lbl (return val) ; exit prog, return val PROGN: Execute each expression and return the value of the last expression. PROG1: Execute each expression and return the value of the first expression. PROG2: Execute each expression and return the value of the second expression. PROG: Create local variables, execute each expression and return the value of the last or as specified in the RETURN statement. Allows GO and RETURN. rev. 11/26/16 Page 7 of 14

13 CONDITIONALS 11 Local Variables (let ((var1 val1) ; initialize var1 to val1 var2 ; initialize var2 to nil exp1 exp2 (let* (vars) exp1 exp2 LET: Creates local variables and executes the expressions in their context. Returns the value of the last expression. LET*: Sames as LET except the variables are assigned sequentially. Previously defined variables may be used in subsequent variable initializations. 12 Defining Functions (defun function-name (arg1 arg2 arg3 exp1 exp2 DEFUN: Define function named function-name with specified arguments, and run the expressions in that context. 12.1 Lambda Argument Types Example argument list Comment (arg1 &optional arg2) arg2 is optional, defaults to null (arg1 &optional (arg2 5)) arg2 is optional, defaults to 5 (arg1 &rest rst) rst is a list containing the remaining arguments (arg1 &key abc def) two key-word arguments, usage: (func :def 55) or (func :abc 44 :def 77) (arg1 &key (abc 88)) keyword argument with default 88 (arg1 &aux var1 var2) two auxiliary or local varables (not arguments) 13 Conditionals In Lisp, conditions are considered true if they are any value other than NIL. Therefore, NIL is considered as false, and all other values are treated as true conditions. (if test exp1 [exp2]) IF: If test expression is true, return exp1. exp2 is optional. If test is false, return exp2 or NIL. rev. 11/26/16 Page 8 of 14

15 ITERATION (cond (test1 exp1 exp2 (test2 exp1 exp2..)... (T exp1 exp2 ) COND: Evalute each testn until one is true. If a true test is found, its expressions are evaluated and the result of the last one is returned. The T test is always true. 14 Numeric Operators Function Description + * / math functions (1+ n) add one (1 n) subtract one ( n) negate number (abs n) absolute value (floor n) return integer rounded down (ceiling n) return integer rounded up (truncate n) return integer portion of number (sqrt n) square root (expt x y) x to power of y (min n1 n2 minimum (max n1 n2 maximum 15 Iteration (loop exp1 exp2 LOOP: Loop indefinitely until a (return exp) is evaluated. (dolist (var lst [rtn]) exp1 exp2 DOLIST: Create new variable var, evaluate lst and set var to successive elements of it. Return rtn when done. (dotimes (var end-val [rtn]) exp1 exp2 (do ((var1 val1 rep1) (test exp1 body1 DOTIMES: Create new variable var and initialize it to 0. Perform body end-val times incrementing var with each iteration. Return rtn when done. DO: Create new variable varn and initialize it to valn. repn is used to provide successive values to varn on each iteration. If test returns non-nil, execute expn and exit DO with the last value. If test fails, execute bodyn and repeat. Also, see PROG rev. 11/26/16 Page 9 of 14

17 FORMAT 16 Displaying (print x) (prin1 x) (princ x) (write x) (pprint x) (terpri) (finish-output) (write-to-string x) (prin1-to-string x) (princ-to-string x) newline, lisp-object, space lisp-object - show as a lisp object object - i.e. no quotes around strings like prin1 except has a lot of options newline, lisp-object BUT pretty prints lisp-object new-line flush output 17 Format (format dest fmt arg1 dest t nil fp string stdout return string output to file output to string with fill pointer fmt ~N% N newlines (default 1) ~c character ~Na string, N wide, left justify, no quotes around strings ~s display as a lisp object ~w use write ~~ ~ ~$ 2 digit floating point ~Nd decimal, N wide, right justify ~N:d decimal, N wide, right justify, add commas ~N,Pf floating point, N wide, P decimal places, right justify ~N,'0d decimal, N wide, zero fill rev. 11/26/16 Page 10 of 14

21 FUNCTION REFERENCES 18 Arrays (make array '(2 3)) create general array with 2x3 dimensions (make array '(2 3) :element-type 'integer) create 2x3 integer array (aref a 2 1) get value at [2,1] index origin 0 (setf (aref a 2 1) val) set array at index [2,1] to val (array-rank a) return the number of dimensions in array (array-dimensions a) get dimensions of array (array-dimension a 0) get the 0th array dimension 19 Hash Tables (make hash table) (gethash key ht) (setf (gethash key ht) val) (gethash key ht) (remhash key ht) (maphash fun ht) (hash-table-count ht) (clrhash ht) create a new hash table get value of key in hash table add a new entry into the hash table test if a key is present remove key / value from hash table enumerate over hash table, fun gets passed key and value return count of entries in ht clear contents of hash table 20 Structures (defstruct structname elm1 elm2 (make-structname keyword-args) (structname elmn instance) (structname p val) create a structure structname with the defined elements create a new instance of structname with possible initialization of the specified elements access elmn of instance (use setf to set) test if val is an instance of structname 21 Function References Obtaining a function reference: #'function name #'(lambda... (function function name) (function (lambda... rev. 11/26/16 Page 11 of 14

23 PACKAGES & MODULES Calling a function reference: (funcall function reference arg1 arg2 (apply function reference '(arg1 arg2 ) 22 Mapping Mapping is the process of iterating a function reference over a group of items. (map result type function reference arg1 list arg2 list result type nil no result 'list return a list of result values function reference argn list #'myfunc #'(lambda... list of arguments. Each argn corresponds to a consecutive argument of function. Each list must be the same length. (mapcar function arg1 list arg2 list Execute function with consecutive elements of argn returning a list of result values. (mapc function arg1 list arg2 list Execute function with consecutive elements of argn returning arg1 list. It does not keep the return values. 23 Packages & Modules Defining a package: (defpackage "X" (:nicknames "Y") (:use "COMMON-LISP") (:export "FUN1" "FUN2") (:shadow "LOAD" "COMPILE-FILE" "EVAL")) (in-package "X") (provide "X") rev. 11/26/16 Page 12 of 14

24 GLOBAL VARIABLES Using a package: A package (pkg) contains exported (esym) and non-exported names (nesym). Package contents are not accessible until they are loaded (i.e. via load or require). After the package is loaded, the symbols in that package are accessible in two different ways depending on whether an use-package has been executed or not. Before use-package: pkg:esym pkg::nesym After use-package: esym pkg::nesym Package and module facilities *package* (list-all-packages) COMMON LISP USER (package name pkg) (find-package name) (symbol-package 'symbol) (defpackage name (in package name) (use package name) *modules* (provide name) (require name &optional path) the current package default user package return the name of the package find package with given name return package symbol is a member of define a new package change to the package name import the exported symbols from package name a list of the currently loaded modules adds name to *modules* to prevent duplicate loads load path if name is not in *modules* 24 Global Variables (defparameter var val [doc string]) (defvar var val [doc string]) set var to val always set var to val only if not already defined rev. 11/26/16 Page 13 of 14

25 MACROS 25 Macros Macros are similar to functions except: 1. the arguments are not evaluated 2. instead of defining operations to execute, macros define lisp code to be executed 3. macros have no runtime overhead because they are resolved at compile time 4. macros take the same variety of arguments types as functions 25.1 defmacro (defmacro macro-name (arg1 arg2 arg3 `(template)) Define a macro named macro-name with unevaluated arguments, create the lisp code, and then execute after creating the code. 25.2 Macro Templates The ` character works like a quote except that the code inside the ` (the template) can have real values inserted into the quoted result. Within the template, the following insertions are in affect:,var,@var insert the value of var splice in the value of var rev. 11/26/16 Page 14 of 14