1 COSC3401-05-10-18 generating functions, templates, and macros Yves Lespérance Adapted from Peter Roosen-Runge.

Slides:



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

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.
Chapter 3 Functional Programming. Outline Introduction to functional programming Scheme: an untyped functional programming language.
Higher Order Functions “I hope you’re convinced, by now, that programming languages with first-class functions let you find more opportunities for abstraction,
Helper functions: when extra arguments are needed Consider this problem: we want a function index_items that takes a list L and gives a number to each.
1 Functional programming Languages And a brief introduction to Lisp and Scheme.
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
Introduction to Artificial Intelligence Lisp Ruth Bergman Fall 2002.
Functional programming: LISP Originally developed for symbolic computing Main motivation: include recursion (see McCarthy biographical excerpt on web site).
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.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
PRACTICAL COMMON LISP Peter Seibel 1.
Rahman Lavaee Mashhadi Mohammad Shadravan. Conditional expressions LISP was the first language to contain a conditional expression In Fortran and Pascal.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
LISP 1.5 and beyond A very quick tour. Data Atoms (symbols) including numbers – All types of numbers including Roman! (well, in the early days) – Syntactically.
Conditionals and Recursion "To iterate is human, to recurse divine." - L. Peter Deutsch.
Common Lisp Macros Read for Input Macros Macro lifetime Macro syntax
1 Lisp Functions –Built-in functions –Defining functions –Function Evaluation and Special Forms defun, if Control statements –Conditional if, cond –Repetition.
ISBN Chapter 15 Functional Programming Languages.
Functional Programming in Scheme and Lisp. Overview In a functional programming language, functions are first class objects. You can create them, put.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
Streams and Lazy Evaluation in Lisp and Scheme. Overview Examples of using closures Delay and force Macros Different models of expression evaluation –
Second-Order Functions and Theorems in ACL2 Alessandro Coglio Workshop 2015 Kestrel Institute.
Functional Programming in Scheme and Lisp.
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 Functional Language or Applicative Language –Achieves its effect by applying functions, either recursively or through composition Powerful, expressive,
LISP Data Types Functional Programming Academic Year Alessandro Cimatti
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
CSE S. Tanimoto Macros 1 Defining Macros in Scheme Extensibility: A language is extensible if the language can be extended. New Scheme control structures.
Operating on Lists Chapter 6. Firsts and Seconds n Transforming list of pairs into two lists –(firsts ‘((1 5) (2 6) (3 7)))  (1 2 3) –(seconds ‘((1 5)
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
1/33 Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
Basic Introduction to Lisp
Macros and general code walkers in Lisp: how useful! or, how useful? Ernst van Waning
1 FP Foundations, Scheme In Text: Chapter Chapter 14: FP Foundations, Scheme Mathematical Functions Def: A mathematical function is a mapping of.
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.
PRACTICAL COMMON LISP Peter Seibel 1.
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.
Operational Semantics of Scheme
Functional Programming Languages
Section 15.4, 15.6 plus other materials
Defining Macros in Lisp
Modern Programming Languages Lecture 20 Fakhar Lodhi
September 4, 1997 Programming Languages (CS 550) Lecture 6 Summary Operational Semantics of Scheme using Substitution Jeremy R. Johnson TexPoint fonts.
The Metacircular Evaluator
FP Foundations, Scheme In Text: Chapter 14.
Functions and Macros.
The Metacircular Evaluator
CSE S. Tanimoto Explicit Function Application
Streams and Lazy Evaluation in Lisp and Scheme
Lisp: Using Functions as Data
John McCarthy Pioneer in AI Also Lisp Formalize common-sense reasoning
6.001 SICP Variations on a Scheme
Defining Macros in Lisp
Clojure Macros.
Announcements Quiz 5 HW6 due October 23
Defining Functions with DEFUN
Peter Seibel Practical Common Lisp Peter Seibel
Abstraction and Repetition
Lisp: Using Functions as Data
Common Lisp II.
Rehearsal: Lazy Evaluation Infinite Streams in our lazy evaluator
Defining Macros in Scheme
Presentation transcript:

1 COSC generating functions, templates, and macros Yves Lespérance Adapted from Peter Roosen-Runge

2 COSC midterm October 20  bring photo ID  closed book; no access to cellphones, PDAs, laptops, etc.  test will be based on the material in the textbook (Ch. 2-8, 10-12, 14), lectures, and readings

3 COSC constructing a pumper  Automating Ch. 11 pumper will create a tail-recursive function and a main function to call it, with arguments: function name, the initial result, and a 'construction' function f f constructs a new (partial) result from a previous (partial) result, with the name of f = |HELP-name|

4 COSC pumper in action  Example: construct both tail-recursive rev (reverse) and its helper function (pumper 'rev NIL ; initial 'CONS ; used to construct result )  recall in rev2 result --> (CONS (FIRST list) result)

5 COSC numerical example  sum of squares: (sumsq list)  slow version: (+ (* (FIRST list) (FIRST list)) (sumsq (REST list))  or define sumsq and |Help-SUMSQ| (pumper 'sumsq 0 '(LAMBDA (x y) (+ (* x x) y)) )

6 COSC the main function  code to construct the main function (DEFUN makeMain (name helper initial) (EVAL (LIST 'DEFUN name '(arglist) (LIST helper 'arglist initial)) ) )

7 COSC make the helper (DEFUN makeHelp (helper f) (EVAL (LIST 'DEFUN helper '(arglist result) (LIST 'IF '(ENDP arglist) 'result (LIST helper '(REST arglist) (LIST ’FUNCALL (LIST 'FUNCTION f) (LIST 'FIRST arglist) result))))) )

8 COSC demo >(makehelp 'helpfun 'CONS) (defun helpfun (arglist result) (if (endp arglist) result (helpfun (rest arglist) (FUNCALL (function CONS) (first arglist) result))))

9 COSC assembling the pieces (DEFUN pumper (name initial f) (LET ((helper (INTERN (FORMAT nil "Help-~a" name)))) (makeMain name helper initial) (makeHelp helper f) )

10 COSC using templates  use template for expressions involving substitutions of values for variables into a fixed structure Lisp's substitution operators  backquote ` : means don’t evaluate unless specified  comma, :,expr means evaluate see form-cons.html

11 COSC template example (DEFUN makeMain (name helper initial) (EVAL ‘(DEFUN,name (arglist) (,helper arglist,initial))) )

12 COSC the complete pumper (DEFUN pumper (name initial f) (LET ((helper (INTERN (FORMAT nil "Help-~a" name)))) (EVAL `(DEFUN,name (arglist) (,helper arglist,initial))) (EVAL `(DEFUN,helper (arglist result) (IF (ENDP arglist) result (,helper (REST arglist) (FUNCALL (FUNCTION,f) (FIRST arglist) result)))) )

13 COSC pumper demo  tail-recursive reverse >(pumper 'rev NIL 'CONS) |Help-REV|  >(rev '(a b c)) (C B A)  (symbol-function '|Help-REV|) = (LAMBDA-BLOCK |Help-REV| (ARGLIST RESULT) (IF (ENDP ARGLIST) RESULT (|Help-REV| (REST ARGLIST) (FUNCALL #'CONS (FIRST ARGLIST) RESULT))))

14 COSC closures  A function may be defined in one context and used in another. If it contains free variables, this may cause problems.  Lisp avoids this by keeping a record of the environment where the function was defined in a closure.

15 COSC closure e.g. (DEFUN gen_adder (n) (FUNCTION (LAMBDA (x) (+ x n)))) (DEFUN eg (n k) (FUNCALL (gen_adder k) n)) >(eg 5 7) 12

16 COSC macros

17 COSC 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  just uninterpreted data structures:  binary trees  'dot' at the root of every sub-tree  atoms at the leaves  macros can be expanded once when function that uses macros is defined or compiled

18 COSC COND is an example >(DESCRIBE ’COND) … special operator with macro definition, has 1 property SYSTEM::MACRO. For more information, evaluate (SYMBOL-PLIST ’COND)… >(SYMBOL-PLIST ’COND) (SYSTEM::MACRO # )

19 COSC step macro evaluation takes two steps expansion s-expression evaluation value MACROEXPANDEVAL >(MACROEXPAND '(COND ((NULL x) 1) ((NULL y) 2) (:OTHERWISE 3))) (IF (NULL X) 1 (IF (NULL Y) 2 (IF :OTHERWISE 3 NIL)))

20 COSC e.g. flambda  often write (FUNCTION (LAMBDA …)); define a macro flambda that abbreviates this. (DEFMACRO flambda (&REST args) (LIST ’FUNCTION (CONS 'LAMBDA args))) ; args will be a list (MACROEXPAND ’(FLAMBDA (X Y) (CONS X Y))) #’(LAMBDA (X Y) (CONS X Y))

21 COSC using a template (DEFMACRO flambda (&REST args) `(FUNCTION (LAMBDA,args)))

22 COSC e.g. 2+ (DEFMACRO 2+ (ARG) `(1+ (1+,arg))) >(MACROEXPAND ’(2+ x)) (1+ (1+ x)) T >(2+ (+ 3 5)) 10

23 COSC destructuring u Macros often destructure their arguments, i.e. extract some of their parts; this is easier if we use structured parameters, lists with named parts >(DEFMACRO cross ((a b) (c d)) `((,a,d) (,b,c))) (MACROEXPAND '(cross (one two) (three four))) ((one four) (two three))

24 COSC fancier example: (DEFMACRO crossdot ((a. b) (c. d)) `((,a,d) (,b,c))) (MACROEXPAND '(crossdot (one two three) (four five six))) ((one (five six)) ((two three) four)  what's happening? what are a, b, c & d bound to?

25 COSC use of macros  support abstraction at little cost, e.g. get- state-field  can add abbreviations that make programming easier, e.g. COND, AND for more than 2 arguments, loop constructs, etc.  can define embedded languages within Lisp with little execution cost  caveat: user must learn the syntax expected by the macros

26 COSC macros vs. functions  a macro is treated internally as a function of one argument  order of evaluation is different, outside- in rather than inside-out, e.g. >(MACROEXPAND ’(2+ (2+ 5)) (1+ (1+ (2+ 5))) T >(2+ (2+ 5)) 9

27 COSC more examples see roExamples.html