Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina

Slides:



Advertisements
Similar presentations
Messiaen Quartet for the end of time And another.
Advertisements

Some non-recursive tricks. The Lambda expression. More on Let, Let*, apply and funcall.
1 Programming Languages and Paradigms Lisp Programming.
Lambda Calculus and Lisp PZ03J. Lambda Calculus The lambda calculus is a model for functional programming like Turing machines are models for imperative.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
A problem with functions: arguments must always have values that can be worked out Whenever we call a function we give it arguments. Lisp then works out.
LISP Programming. LISP – simple and powerful mid-1950’s by John McCarthy at M.I.T. “ LIS t P rocessing language” Artificial Intelligence programs LISP.
Lisp – Introduction יעל נצר מערכות נבונות סמסטר ב' תשס"ו.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
Defining functions in lisp In lisp, all programming is in terms of functions A function is something which –takes some arguments as input –does some computing.
ITERATIVE CONSTRUCTS: DOLIST Dolist is an iterative construct (a loop statement) consisting of a variable declaration and a body The body states what happens.
Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina
Lisp. Versions of LISP Lisp is an old language with many variants –LISP is an acronym for List Processing language Lisp is alive and well today Most modern.
>(setf oldlist ) Constructing a list We know how to make a list in lisp; we simply write it: ‘4321( ) What if we want a new list with that list as a part?
CSE S. Tanimoto Explicit Function Application 1 Explicit Application of Functions, Functional Arguments and Explicit Evaluation Implicit and explicit.
How to load a program file? Lisp programs in Allegro are saved under the file extension.cl. To load a file into the Lisp console, use the following: (load.
Functional programming: LISP Originally developed for symbolic computing First interactive, interpreted language Dynamic typing: values have types, variables.
Introduction to C Programming
Recursion. Definitions I A recursive definition is a definition in which the thing being defined occurs as part of its own definition Example: A list.
COMP 205 – Week 11 Dr. Chunbo Chu. Intro Lisp stands for “LISt Process” Invented by John McCarthy (1958) Simple data structure (atoms and lists) Heavy.
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.
TUTORIAL 2 CSCI3230 ( First Term) By Paco WONG 1.
Genetic Programming.
Yu-Tzu Lin ( 林育慈 )
For Monday Read Chapter 3 Homework: –Lisp handout 2.
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.
CS 355 – PROGRAMMING LANGUAGES Dr. X. Common LISP A combination of many of the features of the popular dialects of LISP around in the early 1980s A large.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
CPS120: Introduction to Computer Science Decision Making in Programs.
Built-in Data Structures in Python An Introduction.
The Loop Macro Many of the CL “functions” are actually macros (let, progn, if, etc) The most complicated macro in CL is probably the Loop macro –The Loop.
Basic LISP Programming Common LISP follows the algorithm below when interacting with users: loop read in an expression from the console; evaluate the expression;
Function Design in LISP. Program Files n LISP programs are plain text –DOS extensions vary; use.lsp for this course n (load “filename.lsp”) n Can use.
Chapter 3 Functions, Events, and Control Structures JavaScript, Third Edition.
Macros “How can you get anything done in [other languages], I think, without macros?” - Paul Graham, 2003.
Lisp Functional Language or Applicative Language –Achieves its effect by applying functions, either recursively or through composition Powerful, expressive,
Predicates, Functions and Files "I suppose I should learn Lisp, but it seems so foreign." - Paul Graham, Nov 1983.
LISP Data Types Functional Programming Academic Year Alessandro Cimatti
Building user-defined functions: the progressive envelopment technique The idea: define combinations of LISP primitives through a sequence of experiments.
Introduction to LISP. Lisp Extensible: It lets you define new operators yourself Lisp programs are expressed as lisp data structures –You can write programs.
JavaScript, Fourth Edition
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
PRACTICAL COMMON LISP Peter Seibel 1.
Control in LISP More on Predicates & Conditionals.
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.
Lecture on Set! And Local CS 2135 Copyright Kathi Fisler, 2002 This material requires Advanced Language Level.
1/33 Basic Scheme February 8, 2007 Compound expressions Rules of evaluation Creating procedures by capturing common patterns.
Introduction to LISP Atoms, Lists Math. LISP n LISt Processing n Function model –Program = function definition –Give arguments –Returns values n Mathematical.
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.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
Artificial Intelligence and Lisp Lecture 6 LiU Course TDDC65 Autumn Semester,
Functional Programming
Basic Scheme February 8, 2007 Compound expressions Rules of evaluation
Scripts & Functions Scripts and functions are contained in .m-files
The Metacircular Evaluator
FP Foundations, Scheme In Text: Chapter 14.
The Metacircular Evaluator (Continued)
CSE S. Tanimoto Explicit Function Application
Streams, Delayed Evaluation and a Normal Order Interpreter
Lisp: Using Functions as Data
Lisp: Using Functions as Data
Modern Programming Languages Lecture 18 Fakhar Lodhi
Common Lisp II.
The general format of case is the following: (case <key form>
Presentation transcript:

Functional Programming COMP2003 A course on functional programming using Common Lisp Dr Eleni Mangina

Macros and evaluation A macro is a way of making a Lisp expression behave as if it were a different, but related, Lisp expression. A macro is a user-definable Lisp procedure which operates by rearranging its arguments into the form of piece of Lisp text, and letting the system evaluate that text. Macros are defined using a very similar notation to that used for functions, except that the Lisp keyword DEFMACRO is used instead of DEFUN The main use of macros is to make some piece of Lisp program behave like some other, systematically related, piece of program – textual re-arrangement is the central idea.

arguments EVAL Body of function result Ordinary function calling arguments Body of function EVAL result S-expression Calling a macro

Suppose we are writing a program in which we often with to carry out a computation which could be roughly summarized as follows: “if this variable has a value, do not change it, but return the value; if it does not yet has a value, assign this value to it, and return that value” It would be helpful if we could define ourselves a single command SET- DEF which does this: > (set-def x 6) 6 > x 6 > (set-def x 12) 6 > x 6 SET-DEF could then be used whenever we need this computation. Attempting to define SET-DEF as a simple DEFUN function would be difficult, since such a function would try to evaluate all its arguments and hence would evaluate the variable name which we are trying to alter. Example

(defun set-def (nm val) ;; This won’t work correctly (setf nm val) ) Various things go wrong with this: > (set-def x 6) ERROR: Unbound variable – X We could try changing it slightly by using the function “boundp” which checks if its argument is currently bound to value; there is also a construct “set”which evaluates its first argument and if the value found is a symbol, it assigns its second argument to that variable. SO: (defun set-def (nm val) ;; this won’t work either (cond ((boundp nm) nm) (t (set nm val))))

(defmacro set-def (var value) (list ‘cond (list(list ‘boundp (list ‘quote var)) var ) (list ‘t (list ‘setf var value) )

(defmacro set-def (var value) (cond((not (symbolp var)) ( error “Non-symbol first argument to SET-DEF: ~s” var )) (t(list‘cond (list (list ‘boundp (lis ‘quote var)) var ) (list ‘t(list ‘setf var value)) )

Things to note about macros Argument evaluation: The arguments passed to a macro are not evaluated as in a normal function, so if a macro were passed a parenthesized expression as one of its parameter-values, say (rest (first l)) then inside the body of the macro, the parameter would have as its value the list which looks like this – its first element would be the symbol rest, and its second element would be a list (first l) with first element first and second element l. The computation extracting the rest of the first of l would not yet have occurred. Result evaluation: Once the macro body has constructed its result, which should be in the form of a bit of program text, that expression gets EVALuated outside the macro, in the environment where the macro was originally called

>(setf var nil) nil >(set-def var (first list3)) This call of the macro will create the result expression: (cond ((boundp ‘var) var) (t(setf var (first list3))) )

>(setf x 3) 3 >(defun test (x) (eval ‘x)) TEST >(test 5) 3 >(defmacro mac-1 () (list ‘print ‘x)) MAC-1 > (defun t1 (x) (mac-1)) T1 > (t1 7) 7

MACROEXPAND This is a very handy built-in function for helping you to debug your macro definitions. The function MACROEXPAND takes any Lisp item as its argument and goes through it “expanding” any macros it finds. > (macroexpand ‘(set-def m nil)) (cond ((bound ‘m) m) (t (setf m nil))) t

WRITING MACROS Write out a sample call of the macro you would like to have, using some illustrative arguments; Then, write out the slab of Lisp code you would like this sample call to be transformed into Decide what part of this sample text should be arguments, as they will vary for each use of the macro and give them symbolic names Lastly, try to write down that transformed form using back quote, comma and comma-at to provide the link to the arguments Hence, a macro might look something like: (defmacro example-mac (arg1 arg2) (cond ((args-invalid arg1 arg2) (error “…”)) (t (create-result (arrange-args arg1 arg2))) )

EXERCISE Define and test a macro of no arguments called cheer which expands to an expression which will print out the string “HOORAY HOORAY”. Try using MACROEXPAND on your defined macro and see what results you get

EXERCISE Define and test a macro of one argument called lastitem which expands to an expression which will return the last element in the value of its argument assuming that the argument evaluates to a list. For example: > (lastitem ‘(a b c d)) d > (lastitem (first (rest (‘(a (b c) d)))) c The result should not be a “list containing the last element”- it should be the element itself

EXERCISE Write a macro which implements a conditional IF-THEN-ELSE statement. This macro (call it IFF) should allow two possible styles of call: (IFF THEN ) (IFF THEN ELSE ) where each test is a single S-expression and so is action. For example: (iff (eql x y) then (return sum)) (iff (atom s) then 1 else (+ (count (first s)) (count (rest s)))) The meaning of these calls is as follows. If the yields a non- nil result when evaluated, the following the THEN symbol is evaluated and the result of that returned as the overall result; if the yields false, and there is no ELSE given, NIL is returned from the IFF statement; if the yields false, and there is an ELSE given, that is evaluated, and the result of that is returned from the IFF statement.

EXERCISE Write a macro WHILE which allows an iterative command. The usage permitted is to be: (while do … ) where the and each is a single S-expression. For example (while (< n 100) do (print (sqrt n)) (setf n (1+ n)) ) The meaning of this is as follows. The sequence of is to be evaluated repeatedly until the yields NIL when evaluated. The test is evaluated before each pass over the, so if it starts off being NIL, no evaluation of the body of the loop occurs. If the ordinary Lisp RETURN construct is evaluated inside the body of the WHILE loop then the loop should terminate in the normal Lisp way, with the argument to RETURN being passed back as the result; if this does not happen the overall result of evalluating the WHILE construct should be NIL.

EXERCISE (Working on more complicated projects) The class of logical expressions correspond to atomic formulae in first order logic, such as: p(a,b) q(a, _x, g(a,c)) s(_x, f(_x,g(_y,a)), d) Each complete formula consists of a predicate together with a sequence of one or more arguments. Each argument must be a term, which is either a constant, a variable, or a function term. Constants and variables are referred to as atomic terms. Variables are represented as symbols starting with underscores, constants as ordinary symbols. A function term consists of a function name followed by a sequence of one or more arguments, each of which must be a term. Functions provided: (term-p x): given an item X, returns T if it is a logical term NIL otherwise (atomic-term-p x): given any item X, returns T if it is an atomic term, NIL otherwise (constant-p x): given a logical term X, returns T if X is a logical variable, NIL otherwise (var-p x): given a logical term X, returns T if X is a logical variable, NIL otherwise (function-term-p x): given a logical term X, returns T if X is a function-term expression of the type being considered here, NIL otherwise. (atomic-formula-p x): given any item X, returns T if X is a logical formula of the type being considered here, NIL otherwise. (function-name x): given a logical term which is a function term, returns the logical constant which is its functor. gives an error if the argument X is not a non-atomic logical term. (predicate-name x): given an atomic logical formula, returns the logical constant which is its functor. Gives an error if the argument X is not an atomic logical formula. (arglist x): given an atomic logical formula or a non-atomic logical term, returns the list of its arguments (in order). Error if argument unsuitable. (make-formula p args): constructs an atomic logical formula whose predicate-name is P and whose argument list is args. Error if arguments unsuitable. (make-function-term f args): constructs an atomic logical term whose function-name is P and whose argument list is args. Error if arguments unsuitable. (newtable) : returns a new table containing no entries (addentry k v t): returns a new table which is the same as the table t except that the value entered for the key k is v

EXERCISE (cont.) (Working on more complicated projects) In this program a (LISP) function called MATCH needs to be implemented, which compares two (atomic) formulae for similarity, taking special account of variables in one of the terms. If the two arguments do not match, it returns NIL, if they match, in the sense that they can be made identical by replacing each logical variable with some (single) term, then a list is being returned containing exactly one element, a “table”in which the keys are the variables and the associated values are those which would make the original arguments identical. The first argument to MATCH may or may not contain logical variables, but an error is indicated if the second argument to MATCH contains logical variables. Both arguments to MATCH must be atomic logical formulae in the sense defined above. An error is indicated if either is not. The result returned is either NIL, if no match is possible, or a list of exactly one element otherwise. That element can be an empty table (if the match involved no variables) or a table of variables and values. A variable cannot be bound to two different values - the program checks this, and the match fails. Examples: (setf p1 (make-formula 'p (list 'x 'x '_Y))) (setf p2 (make-formula 'p (list 'x 'x '()))) ;>>(match p1 p2) ;((_Y NIL)) (setf p3 (make-formula 'p (list '()))) (setf p4 (make-formula 'p (list '()))) ;>>(match p3 p4) ;(NIL) (setf p5 (make-formula 'p (list 'x 'y 'z '() 'a (make-function-term 'f (list 'a 'b 'c)) 'a))) (setf p6 (make-formula 'p (list 'x 'y 'z '() 'a (make-function-term 'f (list 'a 'b 'c)) 'a))) ;>>(match p5 p6) ;(NIL) (setf p7 (make-formula 'p (list 'x 'x 'Y))) (setf p8 (make-formula 'p (list 'x 'y '()))) ;>>(match p7 p8) ;NIL (setf p9 (make-formula 'p (list '_x 'y 'a '_w))) (setf p10 (make-formula 'p (list 'x 'y 'a 'f))) ;>>(match p9 p10) ;((_X X _W F)) (setf p11 (make-formula 'p (list '_x '_y '_z '_w))) (setf p12 (make-formula 'p (list 'x (make-function-term 'f (list 'a 'b 'c)) 'z 'w))) ;>>(match p11 p12) ;((_X X _Y (F A B C) _Z Z _W W))