INF4820. Common Lisp: Closures and Macros
|
|
- Camilla Parker
- 5 years ago
- Views:
Transcription
1 INF4820 Common Lisp: Closures and Macros Erik Velldal University of Oslo Oct. 19, 2010 Erik Velldal INF / 22
2 Topics for Today More Common Lisp A quick reminder: Scope, binding and shadowing Closures Anonymous functions Functions that return functions Memoization Code that generates code: Macros Erik Velldal INF / 22
3 Some Terminology (from Seibel 2005) Binding form A form introducing a variable such as a function definition or a let expression. Scope The area of the program where the variable name can be used to refer to the variable s binding. Lexically scoped variables can be referred to only by code that is textually within their binding form. Shadowing When binding forms are nested and introduce variables of the same name, the innermost binding shadows the outer bindings. Erik Velldal INF / 22
4 A Reminder: Bindings, Scope and Shadowing (setq foo 24) (let ((foo 42) (bar foo)) (print bar)) 24 Erik Velldal INF / 22
5 A Reminder: Bindings, Scope and Shadowing (setq foo 24) (let ((foo 42) (bar foo)) (print bar)) 24 (let* ((foo 42) (bar foo)) (print bar)) 42 Erik Velldal INF / 22
6 A Reminder: Bindings, Scope and Shadowing (setq foo 24) (let ((foo 42) (bar foo)) (print bar)) 24 (let* ((foo 42) (bar foo)) (print bar)) 42 (let ((foo 42)) (let ((bar foo)) (print bar))) 42 Erik Velldal INF / 22
7 Closures Local variables in Common Lisp are based on lexical scoping. But, in CL the concept of closures still makes possible the use of variable references in functions that are called in code outside the scope of the binding form that introduced the variables. Provides many of the advantages of global variables and OO, without the disadvantages. Confused yet? Some examples will help... Erik Velldal INF / 22
8 First, a rather boring example (no closures here) A function count() using the special variable *c*. (defvar *c* 0) (defun count (action &optional (n 1)) (case action (:add (incf *c* n)) (:sub (decf *c* n)) (:print (format t "~&Current count: ~d.~%" *c*)))) (count :add 5) 5 (count :print) Current count: 5. *c* 5 Erik Velldal INF / 22
9 An Example Using Closures A version of count() based on a closure over a free variable. (let ((c 0)) (defun count (action &optional (n 1)) (case action (:add (incf c n)) (:sub (decf c n)) (:print (format t "~&Current count: ~d.~%" c))))) (count :sub 11) -11 (count :add) -10 (count :print) Current count: -10. Erik Velldal INF / 22
10 Combining Closures with Anonymous Functions A function that returns an anonymous function with it s own closure: (defun make-count () (let ((c 0)) # (lambda (action &optional (n 1)) (case action (:add (incf c n)) (:sub (decf c n)) (:print (format t "~&Current count: ~d.~%" c)))))) (setq count1 (make-count)) (setq count2 (make-count)) (funcall count1 :add 5) 5 (funcall count2 :sub) -1 (funcall count1 :print) Current count: 5. (funcall count2 :print) Current count: -1. Erik Velldal INF / 22
11 Closures + Anonymous Functions (Lambda expressions) When a function is defined in a non-null lexical environment, we say that it closes over and captures the bindings of its free variables. The power of closures is often best seen in combination with anonymous functions (as in make-count()). Erik Velldal INF / 22
12 Closures + Anonymous Functions (Lambda expressions) When a function is defined in a non-null lexical environment, we say that it closes over and captures the bindings of its free variables. The power of closures is often best seen in combination with anonymous functions (as in make-count()). In fact, you ve probably already used closures in combination with anonymous functions in settings like: (let ((n 2)) (mapcar # (lambda(x) (expt x n)) (1 2 3))) where # (lambda(x) (expt x n)) closes over the free variable n. Erik Velldal INF / 22
13 Memoization A general technique for speeding up (repeated) calls to a (computationally expensive) function. By caching the computed return values, subsequent calls can retrieve the value by look-up. Erik Velldal INF / 22
14 Memoization A general technique for speeding up (repeated) calls to a (computationally expensive) function. By caching the computed return values, subsequent calls can retrieve the value by look-up. memoize() below takes a function as an argument and returns a new anonymous memoized version of that function, with a closure that contains a hash-table for storing results. Erik Velldal INF / 22
15 Memoization A general technique for speeding up (repeated) calls to a (computationally expensive) function. By caching the computed return values, subsequent calls can retrieve the value by look-up. memoize() below takes a function as an argument and returns a new anonymous memoized version of that function, with a closure that contains a hash-table for storing results. (defun memoize (fn) (let ((cache (make-hash-table :test # equal))) # (lambda (&rest args) (multiple-value-bind (val stored-p) (gethash args cache) (if stored-p val (setf (gethash args cache) (apply fn args))))))) Erik Velldal INF / 22
16 Memoization (cont d) (defun fib (n) (if (or (zerop n) (= n 1)) 1 (+ (fib (- n 1)) (fib (- n 2))))) (setq mem-fib (memoize # fib)) Erik Velldal INF / 22
17 Memoization (cont d) (defun fib (n) (if (or (zerop n) (= n 1)) 1 (+ (fib (- n 1)) (fib (- n 2))))) (setq mem-fib (memoize # fib)) (time (funcall mem-fib 30)) ; real time 27,248 msec ; space allocation: ; 63,594,037 cons cells, 6,721,623,680 other bytes (time (funcall mem-fib 30)) ; real time 0 msec ; space allocation: ; 31 cons cells, 240 other bytes Erik Velldal INF / 22
18 Memoization (cont d) Our memoized Fibonacci function isn t taking full advantage of the memoization... Why? Erik Velldal INF / 22
19 Memoization (cont d) Our memoized Fibonacci function isn t taking full advantage of the memoization... Why? The recursive calls within the function are still using the original non-memoized version! A quick and dirty fix: (setf (symbol-function fib) mem-fib) A good exercise: Write an improved version of memoize() that does this automatically! (PS: It should also save a copy of the original function object so we can unmemoize later.) Erik Velldal INF / 22
20 Memoization (cont d) Our memoized Fibonacci function isn t taking full advantage of the memoization... Why? The recursive calls within the function are still using the original non-memoized version! A quick and dirty fix: (setf (symbol-function fib) mem-fib) A good exercise: Write an improved version of memoize() that does this automatically! (PS: It should also save a copy of the original function object so we can unmemoize later.) Other useful improvements we could make: Specialized data structures and/or equality tests depending on argument type. Canonical sorting of arguments. Support for multiple return values, keyword arguments, etc. Erik Velldal INF / 22
21 Macros Pitch: programs that generate programs. Macro expansion time vs runtime Allows us to control or prevent the evaluation of arguments. Erik Velldal INF / 22
22 Macros Pitch: programs that generate programs. Macro expansion time vs runtime Allows us to control or prevent the evaluation of arguments. Some examples of important Common Lisp built-in macros come in the form of control structures: Conditioning: and, or, if, when, unless, cond, case,... Looping / iteration: do, do*, dolist, dotimes, loop,... Also definitions and assignment: defun, defvar, defparameter, setf,... Erik Velldal INF / 22
23 Defining Our Own Macros With defmacro we can write Lisp code that generates Lisp code. Important operators when writing macros : Quote suppresses evaluation. : Backquote also suppresses evaluation, but..,: A comma inside a backquoted form means the following subform should be evaluated.,@: Comma-at splices lists. Erik Velldal INF / 22
24 Defining Our Own Macros With defmacro we can write Lisp code that generates Lisp code. Important operators when writing macros : Quote suppresses evaluation. : Backquote also suppresses evaluation, but..,: A comma inside a backquoted form means the following subform should be evaluated.,@: Comma-at splices lists. (let ((x 3) (y (1 2))) (a (,(if (oddp x) b c)),@y)) Erik Velldal INF / 22
25 Defining Our Own Macros With defmacro we can write Lisp code that generates Lisp code. Important operators when writing macros : Quote suppresses evaluation. : Backquote also suppresses evaluation, but..,: A comma inside a backquoted form means the following subform should be evaluated.,@: Comma-at splices lists. (let ((x 3) (y (1 2))) (a (,(if (oddp x) b c)),@y)) (a (c) 1 2) Erik Velldal INF / 22
26 Example: A Rather Silly Macro CL-USER(53): (defmacro dolist-reverse ((e list) &rest body) (let ((r (reverse,list))) (dolist (,e r),@body))) DOLIST-REVERSE Erik Velldal INF / 22
27 Example: A Rather Silly Macro CL-USER(53): (defmacro dolist-reverse ((e list) &rest body) (let ((r (reverse,list))) (dolist (,e r),@body))) DOLIST-REVERSE CL-USER(54): (dolist-reverse (x (list 1 2 3)) (print x)) NIL Erik Velldal INF / 22
28 Example: A Rather Silly Macro CL-USER(53): (defmacro dolist-reverse ((e list) &rest body) (let ((r (reverse,list))) (dolist (,e r),@body))) DOLIST-REVERSE CL-USER(54): (dolist-reverse (x (list 1 2 3)) (print x)) NIL All according to plan. Or...? Erik Velldal INF / 22
29 Unintended variable capture can be a pitfall... CL-USER(55): (let ((r 42)) (dolist-reverse (x (list 1 2 3)) (print (list x r)))) (3 (3 2 1)) (2 (3 2 1)) (1 (3 2 1)) NIL Not quite what we wanted... The variable r of the enclosing let-form is shadowed by the let in the macro-expansion! Remedy: Use gensym() at macro expansion time to create unique variable names used in the expansion. Erik Velldal INF / 22
30 gensym to the rescue! Below, r is a variable whose value is the (unique) name of another variable. CL-USER(56): (defmacro dolist-reverse ((e list) &rest body) (let ((r (gensym))) (let ((,r (reverse,list))) (dolist (,e,r),@body)))) DOLIST-REVERSE CL-USER(57): (let ((r 42)) (dolist-reverse (x (list 1 2 3)) (print (list x r)))) (3 42) (2 42) (1 42) Erik Velldal INF / 22
31 Other common pitfalls when writing macros Unintentionally evaluating arguments multiple times. Evaluating arguments in an order unexpected by the caller (i.e. not left to right). A useful debugging tool: macroexpand-1(). Erik Velldal INF / 22
32 Macro-expansion time vs runtime What happens when we use a macro? (1) First the expression specified by the macro definition is built, the so-called macro-expansion... (2)... and then that expression is evaluated in place of the original macro call. Step (1) happens when Lisp parses the program prior to compiling, and step (2) when the code is called at runtime. Two levels of code: Expander code (the code used in the macro to generate its expansion) Expansion code (the code in the expansion itself) Erik Velldal INF / 22
33 A more useful example; dolist-permutations (defmacro dolist-permutations (lists &body body) (if (null (cdr lists)) (dolist,(first (dolist,(first lists) (dolist-permutations,(cdr Erik Velldal INF / 22
34 A more useful example; dolist-permutations (defmacro dolist-permutations (lists &body body) (if (null (cdr lists)) (dolist,(first (dolist,(first lists) (dolist-permutations,(cdr The macro includes calls to other macros, including itself. Using self-reference / recursion in macros requires care to not send the compiler into an infinite loop! Recursion in expander code (as here) vs recursion in expansion code. While expanding dolist-permutations we recur over forms, not values (which are unavailable at expansion time). Erik Velldal INF / 22
35 Using our new macro, dolist-permutations CL-USER(190): (dolist-permutations ((x (a b)) (y (1 2 3)) (z (foo))) (print (list x y z))) (A 1 FOO) (A 2 FOO) (A 3 FOO) (B 1 FOO) (B 2 FOO) (B 3 FOO) NIL Erik Velldal INF / 22
36 For More on Macros... See Paul Graham s On Lisp: (Out of print but freely available online.) Includes several chapters on writing Lisp macros. Erik Velldal INF / 22
FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY,
FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší
More informationINF4820: Algorithms for Artificial Intelligence and Natural Language Processing. More Common Lisp
INF4820: Algorithms for Artificial Intelligence and Natural Language Processing More Common Lisp Stephan Oepen & Murhaf Fares Language Technology Group (LTG) September 6, 2017 Agenda 2 Previously Common
More informationCommon LISP-Introduction
Common LISP-Introduction 1. The primary data structure in LISP is called the s-expression (symbolic expression). There are two basic types of s-expressions: atoms and lists. 2. The LISP language is normally
More informationCommon Lisp. Blake McBride
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
More informationDebugging in LISP. trace causes a trace to be printed for a function when it is called
trace causes a trace to be printed for a function when it is called ;;; a function that works like reverse (defun rev (list) (cons (first (last list)) (rev (butlast list)))) USER: (trace rev) ; note trace
More informationFUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 5. LISP: MAKRA, DATOVÁ STRUKTURA ZÁZNAM
FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 5. LISP: MAKRA, DATOVÁ STRUKTURA ZÁZNAM 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší budoucnosti MACROS Introduction to macro system
More informationAnnouncement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.
Overview Announcement Announcement Lisp Basics CMUCL to be available on sun.cs. You may use GNU Common List (GCL http://www.gnu.org/software/gcl/ which is available on most Linux platforms. There is also
More informationFunctional programming with Common Lisp
Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions
More informationA little bit of Lisp
B.Y. Choueiry 1 Instructor s notes #3 A little bit of Lisp Introduction to Artificial Intelligence CSCE 476-876, Fall 2017 www.cse.unl.edu/~choueiry/f17-476-876 Read LWH: Chapters 1, 2, 3, and 4. Every
More informationINF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals
INF4820: Algorithms for Artificial Intelligence and Natural Language Processing Common Lisp Fundamentals Stephan Oepen & Murhaf Fares Language Technology Group (LTG) August 30, 2017 Last Week: What is
More informationDepartment of Computer and information Science Norwegian University of Science and Technology
Department of Computer and information Science Norwegian University of Science and Technology http://www.idi.ntnu.no/ A Crash Course in LISP MNFIT272 2002 Anders Kofod-Petersen anderpe@idi.ntnu.no Introduction
More informationFunctional programming techniques
Functional programming techniques o Currying o Continuations o Streams. Lazy evaluation Currying o Haskell B. Curry. o Second-order programming: o Functions that return other functions. o Example: A two-arguments
More informationRecursion & Iteration
Recursion & Iteration York University Department of Computer Science and Engineering 1 Overview Recursion Examples Iteration Examples Iteration vs. Recursion Example [ref.: Chap 5,6 Wilensky] 2 Recursion
More informationSymbolic Programming. Dr. Zoran Duric () Symbolic Programming 1/ 89 August 28, / 89
Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic expressions. Symbolic manipulation: you do it all the
More informationRobot Programming with Lisp
4. Functional Programming: Higher-order Functions, Map/Reduce, Lexical Scope Institute for Artificial University of Bremen 9 of November, 2017 Functional Programming Pure functional programming concepts
More informationA Brief Introduction to Common Lisp
A Brief Introduction to Common Lisp David Gu Schloer Consulting Group david_guru@gty.org.in A Brief History Originally specified in 1958, Lisp is the second-oldest highlevel programming language in widespread
More informationCS 480. Lisp J. Kosecka George Mason University. Lisp Slides
CS 480 Lisp J. Kosecka George Mason University Lisp Slides Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic
More informationCommon LISP Tutorial 1 (Basic)
Common LISP Tutorial 1 (Basic) CLISP Download https://sourceforge.net/projects/clisp/ IPPL Course Materials (UST sir only) Download https://silp.iiita.ac.in/wordpress/?page_id=494 Introduction Lisp (1958)
More informationMeet the Macro. a quick introduction to Lisp macros. Patrick Stein / TC Lisp Users Group /
Meet the Macro a quick introduction to Lisp macros Patrick Stein / TC Lisp Users Group / 2009-07-14 Attack Plan Some other things called macros First look at Lisp macros More advanced macros Uh-oh, my
More informationFunctional Programming with Common Lisp
Functional Programming with Common Lisp Kamen Tomov ktomov@hotmail.com July 03, 2015 Table of Contents What is This About? Functional Programming Specifics Is Lisp a Functional Language? Lisp Says Hi Functional
More information19 Machine Learning in Lisp
19 Machine Learning in Lisp Chapter Objectives Chapter Contents ID3 algorithm and inducing decision trees from lists of examples. A basic Lisp implementation of ID3 Demonstration on a simple credit assessment
More informationCS 842 Ben Cassell University of Waterloo
CS 842 Ben Cassell University of Waterloo Recursive Descent Re-Cap Top-down parser. Works down parse tree using the formal grammar. Built from mutually recursive procedures. Typically these procedures
More informationAllegro CL Certification Program
Allegro CL Certification Program Lisp Programming Series Level I Presented by 1 About David Margolies Manager, Documentation, Franz Inc Been working with Lisp since 1984 dm@franz.com 2 About Franz Inc.
More informationA Genetic Algorithm Implementation
A Genetic Algorithm Implementation Roy M. Turner (rturner@maine.edu) Spring 2017 Contents 1 Introduction 3 2 Header information 3 3 Class definitions 3 3.1 Individual..........................................
More informationCSCI 2210: Programming in Lisp. Progn. Block. CSCI Programming in Lisp; Instructor: Alok Mehta 1. ANSI Common Lisp, Chapters 5-10
CSCI 2210: Programming in Lisp ANSI Common Lisp, Chapters 5-10 CSCI 2210 - Programming in Lisp; Instructor: Alok Mehta; 4.ppt 1 Progn Progn Creates a block of code Expressions in body are evaluated Value
More informationArtificial Intelligence Programming
Artificial Intelligence Programming Rob St. Amant Department of Computer Science North Carolina State University Lisp basics NC State University 2 / 99 Why Lisp? Some recent Lisp success stories include
More informationLambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky.
λ Calculus Basis Lambda Calculus and Lambda notation in Lisp II Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky Mathematical theory for anonymous functions» functions that have
More informationLisp Basic Example Test Questions
2009 November 30 Lisp Basic Example Test Questions 1. Assume the following forms have been typed into the interpreter and evaluated in the given sequence. ( defun a ( y ) ( reverse y ) ) ( setq a (1 2
More informationAnnouncements. Today s Menu
Announcements 1 Today s Menu Finish Introduction to ANNs (original material by Dr. Mike Nechyba) > Slides 58-60 > Adjusting the Learning Rate Loose Ends in > Lambda Expressions Review > I/O Functions >
More informationRacket: Macros. Advanced Functional Programming. Jean-Noël Monette. November 2013
Racket: Macros Advanced Functional Programming Jean-Noël Monette November 2013 1 Today Macros pattern-based macros Hygiene Syntax objects and general macros Examples 2 Macros (According to the Racket Guide...)
More informationJatha. Common Lisp in Java. Ola Bini JRuby Core Developer ThoughtWorks Studios.
Jatha Common Lisp in Java Ola Bini JRuby Core Developer ThoughtWorks Studios ola.bini@gmail.com http://olabini.com/blog Common Lisp? Common Lisp? ANSI standard Common Lisp? ANSI standard Powerful Common
More informationProject 2: Scheme Interpreter
Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same
More informationModern Programming Languages. Lecture LISP Programming Language An Introduction
Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation
More informationLecture Notes on Lisp A Brief Introduction
Why Lisp? Lecture Notes on Lisp A Brief Introduction Because it s the most widely used AI programming language Because Prof Peng likes using it Because it s good for writing production software (Graham
More informationExtra Lecture #7: Defining Syntax
Extra Lecture #7: Defining Syntax In effect, function and class definitions extend the Python language by adding new commands and data types. However, these are highly constrained extensions. For example,
More informationFunctional Programming. Pure Functional Programming
Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).
More informationEvery language has its own scoping rules. For example, what is the scope of variable j in this Java program?
Lexical Binding There are two ways a variable can be used in a program: As a declaration As a "reference" or use of the variable Scheme has two kinds of variable "declarations" -- the bindings of a let-expression
More informationFunctions, Conditionals & Predicates
Functions, Conditionals & Predicates York University Department of Computer Science and Engineering 1 Overview Functions as lambda terms Defining functions Variables (bound vs. free, local vs. global)
More information(defun fill-nodes (nodes texts name) (mapcar #'fill-node (replicate-nodes nodes (length texts) name) texts))
PROBLEM NOTES Critical to the problem is noticing the following: You can t always replicate just the second node passed to fill-nodes. The node to be replicated must have a common parent with the node
More informationa little more on macros sort of like functions, but..
a little more on macros 1 sort of like functions, but.. one of the most interesting but tricky aspects of Lisp. unlike functions, macros don't evaluate their arguments; they compute on unevaluated expressions
More informationNames, Bindings, Scopes
Names, Bindings, Scopes Variables In imperative l Language: abstractions of von Neumann machine Variables: abstraction of memory cell or cells Sometimes close to machine (e.g., integers), sometimes not
More information(defvar *state* nil "The current state: a list of conditions.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; GPS engine for blocks world ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar *dbg-ids* nil "Identifiers used by dbg") (defvar *state* nil "The current state: a list of conditions.")
More informationUMBC CMSC 331 Final Exam
UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy
More informationFunctional Languages. CSE 307 Principles of Programming Languages Stony Brook University
Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work
More informationLoading Multiple Versions of an ASDF System in the Same Lisp Image
Loading Multiple Versions of an ASDF System in the Same Lisp Image Vsevolod Domkin 10 th European Lisp Symposium 2017-04-03 It all started with... I'm yet to see a name conflict in Lisp that can't be solved
More informationCSCI337 Organisation of Programming Languages LISP
Organisation of Programming Languages LISP Getting Started Starting Common Lisp $ clisp i i i i i i i ooooo o ooooooo ooooo ooooo I I I I I I I 8 8 8 8 8 o 8 8 I \ `+' / I 8 8 8 8 8 8 \ `-+-' / 8 8 8 ooooo
More informationCIS4/681 { Articial Intelligence 2 > (insert-sort '( )) ( ) 2 More Complicated Recursion So far everything we have dened requires
1 A couple of Functions 1 Let's take another example of a simple lisp function { one that does insertion sort. Let us assume that this sort function takes as input a list of numbers and sorts them in ascending
More informationNotes on Higher Order Programming in Scheme. by Alexander Stepanov
by Alexander Stepanov August 1986 INTRODUCTION Why Scheme? Because it allows us to deal with: 1. Data Abstraction - it allows us to implement ADT (abstact data types) in a very special way. The issue of
More informationStreams and Lazy Evaluation in Lisp
Streams and Lazy Evaluation in Lisp Overview Different models of expression evaluation Lazy vs. eager evaluation Normal vs. applicative order evaluation Computing with streams in Lisp Motivation Unix Pipes
More informationUMBC CMSC 331 Final Exam
UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy
More informationImperative, OO and Functional Languages A C program is
Imperative, OO and Functional Languages A C program is a web of assignment statements, interconnected by control constructs which describe the time sequence in which they are to be executed. In Java programming,
More informationLambda Calculus see notes on Lambda Calculus
Lambda Calculus see notes on Lambda Calculus Shakil M. Khan adapted from Gunnar Gotshalks recap so far: Lisp data structures basic Lisp programming bound/free variables, scope of variables Lisp symbols,
More informationMore Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list?
More Scheme CS 331 Quiz 1. What is (car ((2) 3 4))? (2) 2. What is (cdr ((2) (3) (4)))? ((3)(4)) 3. What is (cons 2 (2 3 4))? (2 2 3 4) 4. What is the length of the list (()()()())? 4 5. Which element
More informationLecture #2 Kenneth W. Flynn RPI CS
Outline Programming in Lisp Lecture #2 Kenneth W. Flynn RPI CS Items from last time Recursion, briefly How to run Lisp I/O, Variables and other miscellany Lists Arrays Other data structures Jin Li lij3@rpi.edu
More informationLFE - a lisp on the Erlang VM
Robert Virding Principle Language Expert at Erlang Solutions Ltd. LFE - a lisp on the Erlang VM What LFE isn t It isn t an implementation of Scheme It isn t an implementation of Common Lisp It isn t an
More informationAllegro CL Certification Program
Allegro CL Certification Program Lisp Programming Series Level I Session 1.3.1 David Margolies Manipulating Lists 9/16/2010 1 What is a List? An ordered (possibly empty) collection of things in a particular
More informationXLISP PLUS. Reference Manual. Version 3.0
XLISP PLUS Reference Manual Version 3.0 XLISP-PLUS: Another Object-oriented Lisp Version 3.0 May 12, 2011 Tom Almy tom@almy.us Portions of this manual and software are from XLISP which is Copyright (c)
More informationLexical vs. Dynamic Scope
Intro Lexical vs. Dynamic Scope where do I point to? Remember in Scheme whenever we call a procedure we pop a frame and point it to where the procedure points to (its defining environment). This is called
More informationEvaluating Scheme Expressions
Evaluating Scheme Expressions How Scheme evaluates the expressions? (procedure arg 1... arg n ) Find the value of procedure Find the value of arg 1 Find the value of arg n Apply the value of procedure
More informationAllegro CL Certification Program
Allegro CL Certification Program Lisp Programming Series Level I Review David Margolies 1 Summary 1 A lisp session contains a large number of objects which is typically increased by user-created lisp objects
More informationObject Oriented Programming (OOP)
Object Oriented Programming (OOP) o New programming paradigm o Actions Objects o Objects Actions o Object-oriented = Objects + Classes + Inheritance Imperative programming o OOP (Object-Oriented Programming)
More informationSome Naughty Bits. Jeremy Brown. January 7-8, 2003
Advanced Scheme Techniques Some Naughty Bits Jeremy Brown January 7-8, 2003 Page 1 Jeremy H. Brown January 7-8, 2003 Acknowledgements Jonathan Bachrach, Alan Bawden, Chris Hanson, Neel Krishnaswami, and
More informationSection 10: LISP to Scheme. Evolution of Software Languages
Section Evolution of Software Languages Theo D'Hondt Bachelor of Computer Science Faculty of Sciences and Bio-Engineering Sciences Vrije Universiteit Brussel Academic Year 2015-2016 Evolution of Software
More informationIntroduction to Lisp
Last update: February 16, 2010 Introduction to Lisp Dana Nau Dana Nau 1 Outline I assume you know enough about computer languages that you can learn new ones quickly, so I ll go pretty fast If I go too
More informationMIDTERM EXAMINATION - CS130 - Spring 2005
MIDTERM EAMINATION - CS130 - Spring 2005 Your full name: Your UCSD ID number: This exam is closed book and closed notes Total number of points in this exam: 231 + 25 extra credit This exam counts for 25%
More informationAn introduction to Scheme
An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize
More informationBasics of Using Lisp! Gunnar Gotshalks! BLU-1
Basics of Using Lisp BLU-1 Entering Do Lisp work Exiting Getting into and out of Clisp % clisp (bye)» A function with no arguments» CTRL d can also be used Documentation files are in the directory» /cse/local/doc/clisp
More informationLISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits.
LISP Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits. From one perspective, sequences of bits can be interpreted as a code for ordinary decimal digits,
More information11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT
Functional programming FP Foundations, Scheme (2 In Text: Chapter 15 LISP: John McCarthy 1958 MIT List Processing => Symbolic Manipulation First functional programming language Every version after the
More information1 CLWEB INTRODUCTION 1
1 CLWEB INTRODUCTION 1 1. Introduction. This is CLWEB, a literate programming system for Common Lisp by Alex Plotnick plotnick@cs.brandeis.edu. It is modeled after the CWEB system by Silvio Levy and Donald
More informationTAIL RECURSION, SCOPE, AND PROJECT 4 11
TAIL RECURSION, SCOPE, AND PROJECT 4 11 COMPUTER SCIENCE 61A Noveber 12, 2012 1 Tail Recursion Today we will look at Tail Recursion and Tail Call Optimizations in Scheme, and how they relate to iteration
More informationSCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017
SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationThis should prevent residual sexism, racism, favoritism lurking in the unconscious of your professor & TA from biasing grading!!
NAME login: Signature: Computer Science and Engineering 150 Programming Languages for Artificial Intelligence Tuesday, November 5, 2002: DON T FORGET TO VOTE!!! FIRST MIDTERM EXAM DO NOT TURN THIS PAGE
More informationSymbolic Computation and Common Lisp
Symbolic Computation and Common Lisp Dr. Neil T. Dantam CSCI-56, Colorado School of Mines Fall 28 Dantam (Mines CSCI-56) Lisp Fall 28 / 92 Why? Symbolic Computing: Much of this course deals with processing
More informationSummer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define
CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationCS 360 Programming Languages Interpreters
CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like
More information(defmacro while (condition &body body) `(iterate loop () (if,condition (loop)))))
; PARCIL - A Parser for C syntax In Lisp version 0.1a copyright (c) 1992 by Erann Gat, all rights reserved This program is free software; you can redistribute it and/or modify it under the terms of the
More informationCL1 Manual. Alan Bawden ABSTRACT
Massachusetts Institute of Technology Artificial Intelligence Laboratory Working Paper 254 September, 1983 CL1 Manual Alan Bawden ABSTRACT CL1 is a prototype language for programming a Connection Machine.
More informationRobot Programming with Lisp
2. Imperative Programming Institute for Artificial University of Bremen Lisp the Language LISP LISt Processing language 2 Lisp the Language LISP LISt Processing language (LISP Lots of Irritating Superfluous
More informationSCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015
SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,
More informationMacroexpand-All: An Example of a Simple Lisp Code Walker
Macroexpand-All: An Example of a Simple Lisp Code Walker Richard C. Waters Mitsubishi Electric Research Laboratories 201 Broadway; Cambridge MA 02139 Dick@MERL.COM If you like to write Lisp macros, or
More informationAssociative Database Managment WIlensky Chapter 22
Associative Database Managment WIlensky Chapter 22 DB-1 Associative Database An associative database is a collection of facts retrievable by their contents» Is a poodle a dog? Which people does Alice manage?»
More information(defmacro for ((var start stop) &body body) (do ((,var,start (1+,var)) (limit,stop)) ((>,var
9 Variable Capture Macros are vulnerable to a problem called variable capture. Variable capture occurs when macroexpansion causes a name clash: when some symbol ends up referring to a variable from another
More informationIntroduction to LISP. York University Department of Computer Science and Engineering. York University- CSE V.
Introduction to LISP York University Department of Computer Science and Engineering York University- CSE 3401- V. Movahedi 11_LISP 1 Introduction to LISP Evaluation and arguments S- expressions Lists Numbers
More informationReview of Functional Programming
Review of Functional Programming York University Department of Computer Science and Engineering 1 Function and # It is good programming practice to use function instead of quote when quoting functions.
More informationTopic III. LISP : functions, recursion, and lists References: Chapter 3 of Concepts in programming languages by J. C. Mitchell. CUP, 2003.
Topic III LISP : functions, recursion, and lists References: Chapter 3 of Concepts in programming languages by J. C. Mitchell. CUP, 2003. Chapters 5( 4.5) and 13( 1) of Programming languages: Design and
More informationFUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE,
FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší budoucnosti L I S P - Introduction L I S P
More informationAssociative Database Managment
Associative Database Managment WIlensky Chapter 22 DB-1 Associative Database An associative database is a collection of facts retrievable by their contents» Is a poodle a dog? Which people does Alice manage?»
More informationComputer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing
Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs Lexical addressing The difference between a interpreter and a compiler is really two points on a spectrum of possible
More information4. Functional Programming Language-Oriented Programming
4. Functional Programming Language-Oriented Programming Prof. Dr. Bernhard Humm Faculty of Computer Science Hochschule Darmstadt University of Applied Sciences 1 Retrospect: LOP the big picture What is
More informationScheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7
Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions
More informationLecture #5 Kenneth W. Flynn RPI CS
Outline Programming in Lisp Lecture #5 Kenneth W. Flynn RPI CS We've seen symbols in three contexts so far: > (setf sym ) (let ((sym ))...) >'Sym SYM -- Context The first of these refers to a special (or
More informationPutting the fun in functional programming
CM20167 Topic 4: Map, Lambda, Filter Guy McCusker 1W2.1 Outline 1 Introduction to higher-order functions 2 Map 3 Lambda 4 Filter Guy McCusker (1W2.1 CM20167 Topic 4 2 / 42 Putting the fun in functional
More informationLisp. Versions of LISP
Lisp Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks is based on Common Lisp Scheme is one of the major
More information6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson
6.184 Lecture 4 Interpretation Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson 1 Interpretation Parts of an interpreter Arithmetic calculator
More informationA Quick Introduction to Common Lisp
CSC 244/444 Notes last updated ug. 30, 2016 Quick Introduction to Common Lisp Lisp is a functional language well-suited to symbolic I, based on the λ-calculus and with list structures as a very flexible
More informationMidterm Examination (Sample Solutions), Cmput 325
Midterm Examination (Sample Solutions, Cmput 325 [15 marks] Consider the Lisp definitions below (defun test (L S (if (null L S (let ((New (add (cdar L S (test (cdr L New (defun add (A S (if (null S (cons
More informationAlgorithms for AI and NLP (INF4820 Lisp & FSAs)
S NP Det N VP V The dog barked LTOP h 1 INDEX e 2 def q rel bark v rel prpstn m rel LBL h 4 dog n rel LBL h RELS LBL h 1 ARG0 x 5 LBL h 9 8 ARG0 e MARG h 3 RSTR h 6 ARG0 x 2 5 ARG1 x BODY h 5 7 HCONS h
More informationFall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write
More informationConcepts of programming languages
Concepts of programming languages Lecture 7 Wouter Swierstra 1 Last time Relating evaluation and types How to handle variable binding in embedded languages? 2 DSLs: approaches A stand-alone DSL typically
More information