Defining Macros in Lisp

Slides:



Advertisements
Similar presentations
09 Examples Functional Programming. Tower of Hanoi AB C.
Advertisements

CS 63 LISP Philip Greenspun's Tenth* Rule of Programming:
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.
Scheme in Scheme. Why implement Scheme in Scheme  Implementing a language is a good way to learn more about programming languages  Interpreters are.
Functional Programming. Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends.
1 Programming Languages and Paradigms Lisp Programming.
CSE S. Tanimoto Macros 1 Defining Macros in Lisp Extensibility: A language is extensible if the language can be extended. New Lisp control structures.
CSE S. Tanimoto Explicit Function Application 1 Explicit Application of Functions, Functional Arguments and Explicit Evaluation Implicit and explicit.
Symbolic Expressions (S Expressions) Syntax: Opening and Closing parenthesis having elements in between. List represented in LISP: (A B2 C3 Shahid) (A.
PRACTICAL COMMON LISP Peter Seibel 1.
CSE S. Tanimoto Lisp Lisp S-Expressions: ATOMs Every Lisp object is either an ATOM or a CONS Symbols and numbers are kinds of atoms: X, APPLE,
Common Lisp Macros Read for Input Macros Macro lifetime Macro syntax
CSE 341, S. Tanimoto Lisp Defining Functions with DEFUN Functions are the primary abstraction mechanism available in Lisp. (Others are structures.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
Lecture 1-2CS251: Intro to AI/Lisp II “And now for something completely different…”
Macros “How can you get anything done in [other languages], I think, without macros?” - Paul Graham, 2003.
CSE S. Tanimoto Lisp Defining Macros in Lisp Extensibility: A language is extensible if the language can be extended. New Lisp control structures.
Lisp Files, Arrays, and Macros CIS 479/579 Bruce R. Maxim UM-Dearborn.
Introduction to LISP. Lisp Extensible: It lets you define new operators yourself Lisp programs are expressed as lisp data structures –You can write programs.
CSE S. Tanimoto Macros 1 Defining Macros in Scheme Extensibility: A language is extensible if the language can be extended. New Scheme control structures.
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
CSE S. Tanimoto More-Concepts - 1 More Programming Language Concepts Currying Lazy Evaluation Polymorphism.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
1 COSC generating functions, templates, and macros Yves Lespérance Adapted from Peter Roosen-Runge.
Basic Introduction to Lisp
Macros and general code walkers in Lisp: how useful! or, how useful? Ernst van Waning
CSE S. Tanimoto Lisps's Basic Functionality 1 LISP: Basic Functionality S-expressions Conses Lists Predicates Evaluation and quoting Conditional.
CSE 341, S. Tanimoto Lisp Explicit Application of Functions and Functional Arguments In Lisp, functions can be passed as arguments to other functions.
Forms Writing your own procedures CS 480/680 – Comparative Languages.
Clojure Macros. Homoiconicity All versions of Lisp, including Clojure, are homoiconic This means that there is no difference between the form of the data.
Macros Forms that the compiler expands into code ● Decide if the macro is really necessary ● Write down the syntax of the macro ● Figure out what the macro.
Feb 17, 2015 Clojure 4. Macros Code is data We have heard this before. It is what makes Lisp so amenable to the use of macros. Examples from Mastering.
Artificial Intelligence and Lisp Lecture 6 LiU Course TDDC65 Autumn Semester,
Lisp S-Expressions: ATOMs
Defining Macros in Lisp
Modern Programming Languages Lecture 20 Fakhar Lodhi
Chapter 15 – Functional Programming Languages
The Metacircular Evaluator
Dynamic Scoping Lazy Evaluation
The Metacircular Evaluator
Scheme: Basic Functionality
CSE S. Tanimoto Introduction
Abstraction and Repetition
Modern Programming Languages Lecture 20 Fakhar Lodhi
The Metacircular Evaluator (Continued)
CSE S. Tanimoto Explicit Function Application
6.001 SICP Further Variations on a Scheme
CSE S. Tanimoto Introduction
Explicit Application of Procedures, and Explicit Evaluation
Functional Programming Concepts
Lecture #9 מבוא מורחב.
Lisp: Using Functions as Data
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
CSE S. Tanimoto Introduction
Functional Programming Concepts
Lisp: Representation of Data
Clojure Macros.
Defining Functions with DEFUN
Abstraction and Repetition
Lisp: Using Functions as Data
LISP: Basic Functionality
Functional Programming Concepts
LISP: Basic Functionality
Common Lisp II.
LISP: Basic Functionality
Lisp.
More Scheme CS 331.
Defining Macros in Scheme
Lisp: Representation of Data
Abstraction and Repetition
Presentation transcript:

Defining Macros in Lisp Extensibility: A language is extensible if the language can be extended. New Lisp control structures can be created using macros. A macro form is evaluated in a special way: First the macro form is expanded by applying the macro-expansion function (given in the definition) to the arguments. Then the resulting expression is evaluated again. CSE 341 -- S. Tanimoto Macros

CSE 341 -- S. Tanimoto Macros Example: NULLIFY > (setq x 5) 5 > x > (defmacro nullify (symbol) (list 'setq symbol 'nil) ) NULLIFY > (nullify x) NIL CSE 341 -- S. Tanimoto Macros

Macro Expansion for NULLIFY By defining the macro NULLIFY, we have actually defined a function, but it’s not named NULLIFY. It’s called the macro expansion function for NULLIFY. When the macro NULLIFY is called, its macro expansion function is applied to the macro argument. And then that result is evaluated. We can see the intermediate result if we use the built-in function MACROEXPAND. > (macroexpand '(nullify total)) (SETQ TOTAL NIL) T ; Two values are returned. ; The first is the expansion itself. ; Second, we have T, since a macro form was expanded. CSE 341 -- S. Tanimoto Macros

CSE 341 -- S. Tanimoto Macros Macro Call Evaluation (nullify total) 1. The arguments (unevaluated) are passed to the macro expansion function. SYMBOL gets as its binding the symbol TOTAL. 2. The expansion function is applied. Any macro forms within the expansion are themselves expanded. (SETQ TOTAL NIL) 3. The result of expansion is itself evaluated. NIL CSE 341 -- S. Tanimoto Macros

CSE 341 -- S. Tanimoto Macros Example: IF-N-Z-P > (defmacro if-n-z-p (numexpr negform zeroform posform) (list 'cond (list (list '< (eval numexpr) 0) negform) (list (list '= (eval numexpr) 0) zeroform) (list (list '> (eval numexpr) 0) posform) (list t '(print 'error)) ) ) CSE 341 -- S. Tanimoto Macros

Macro Expansion: IF-N-Z-P > (macroexpand '(if-n-z-p (* 3 -5) -35 'zero 37)) (IF (< -15 0) -35 (IF (= -15 0) 'ZERO (IF (> -15 0) 37 (PRINT 'ERROR)))) T Note that COND, which is implemented as a macro in GCL, was expanded, too. The macro expansion for this macro is a little inefficient, because the condition is always evaluated 3 times. We could rewrite the macro to perform the expansion once, save the value in a local variable, and access it three times. But, what should we name the variable? The safe thing to do is use GENSYM to synthesize a unique symbol and use it. (An optional exercise - and fairly tricky). CSE 341 -- S. Tanimoto Macros

Example: PUSH (actually built-in) > (defmacro push (element stack) (list 'if (list 'null stack) (list 'setq stack (list 'quote (list element))) (list 'cons element stack)) ) ) CSE 341 -- S. Tanimoto Macros

Macro Expansion for PUSH > (macroexpand '(push 5 s)) (IF (NULL S) (SETQ S '(5)) (SETQ S (CONS 5 S))) T ; again, the 2nd value is T ; since a macro form was expanded CSE 341 -- S. Tanimoto Macros

Full Macro-form Evaluation First the form is fully expanded, and then the resulting form is evaluated. > (setq s nil) NIL > (push 5 s) (5) > (push '(next element) s) ((NEXT ELEMENT) 5) CSE 341 -- S. Tanimoto Macros

CSE 341 -- S. Tanimoto Macros Example: TWICE Takes any number of forms and evaluates them all once and then all again. > (defmacro twice (&rest forms) (append '(progn) forms forms) ) TWICE > (twice (format t "Macros are powerful~%") (format t "Aren’t they?~%") ) Macros are powerful Aren’t they? NIL > CSE 341 -- S. Tanimoto Macros

CSE 341 -- S. Tanimoto Macros Example: AVERAGE Takes two numeric arguments and returns the mean. > (defmacro average (num1 num2) (list '/ (list '+ (eval num1) (eval num2)) 2) ) AVERAGE > (macroexpand '(average 2 (* 5 4))) (/ (+ 2 20)) T > (average 2 (* 5 4)) 11 Arguments to macros are not automatically evaluated, as they are in function calls. CSE 341 -- S. Tanimoto Macros

CSE 341 -- S. Tanimoto Macros Example: SET-TO-ONE Takes any number of arguments, which must be symbols, and gives each the value 1. > (defmacro set-to-one (&rest symbols) (append '(progn) (mapcar #'(lambda (s) (list 'setq s 1)) symbols))) > (macroexpand '(set-to-one x y z)) (PROGN (SETQ X 1) (SETQ Y 1) (SETQ Z 1)) T > (set-to-one x y z) 1 > y CSE 341 -- S. Tanimoto Macros

Backquote and Comma Syntax Allows the body of a macro to look like the expanded form. > (defmacro push (element stack) ‘(if (null ,stack) (setq ',stack '(,element)) (setq ,stack (cons ,element ,stack)) ) ) >(macroexpand '(push 5 s)) (IF (NULL S)(SETQ 'S '(5))(SETQ S (CONS 5 S))) T Backquote is like QUOTE but it allows subexpressions preceded by a comma to be evaluated. CSE 341 -- S. Tanimoto Macros

CSE 341 -- S. Tanimoto Macros Example: ENQUEUE Like PUSH, but puts the new element at the end of the list. > (defmacro enqueue (item lst) ‘(if (null ,lst) (setq ',lst '(,item)) (nconc ,lst (list ,item)) ) ) > (setq q '(a b c)) (A B C) > (enqueue 'd q) (A B C D) CSE 341 -- S. Tanimoto Macros

CSE 341 -- S. Tanimoto Macros Example: SELECT Each clause is a list that begins with a value that might equal that of OBJECT. These value are tested in turn, and the first one that is equal to OBJECT has its remaining clause elements evaluated, and the value of the last of these is returned. > (select 5 (4 "too small") (5 "just right" "five") (6 "six") ) "five" CSE 341 -- S. Tanimoto Macros

CSE 341 -- S. Tanimoto Macros Example: SELECT Note that the backquote doesn’t have to be at top-level. Also note the use of the dot (.) which means that the list that follows should be spliced into the current list. (defmacro select (object &rest clauses) (append '(cond) (mapcar #'(lambda (clause) `((equal (first ',clause) ,object) . ,(rest clause)) ) clauses))) CSE 341 -- S. Tanimoto Macros

CSE 341 -- S. Tanimoto Macros Language Extension A new control structure, such as SELECT, is a good example of extending a language. Most languages allow user-defined functions, which provide a first level of language extension. By providing a coherent set of extensions to Lisp, typically containing both macro and function definitions, you can create an embedded language (EL). If you need a domain-specific language, an EL may be the way to go, because: The EL takes advantage of its host language, Lisp, for its basic syntax, parsing, and for handling lots of generic functionality. Example domains: knowledge representation, automatic theorem proving, text-processing, combinatorics, gene sequence processing. CSE 341 -- S. Tanimoto Macros