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

Similar documents
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Í 3. LISP: ZÁKLADNÍ FUNKCE, POUŽÍVÁNÍ REKURZE,

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

INF4820. Common Lisp: Closures and Macros

A little bit of Lisp

Common Lisp. Blake McBride

Recursion & Iteration

Common LISP-Introduction

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

A Brief Introduction to Common Lisp

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

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

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

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

Jatha. Common Lisp in Java. Ola Bini JRuby Core Developer ThoughtWorks Studios.

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

Common LISP Tutorial 1 (Basic)

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

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

19 Machine Learning in Lisp

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 1. ÚVOD DO PŘEDMĚTU, LAMBDA CALCULUS

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Robot Programming with Lisp

Functions, Conditionals & Predicates

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

Structure Programming in Lisp. Shared Structure. Tailp. Shared Structure. Top-Level List Structure

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

Announcements. Today s Menu

Streams and Lazy Evaluation in Lisp

Lecture Notes on Lisp A Brief Introduction

Associative Database Managment WIlensky Chapter 22

Associative Database Managment

Introduction to Lisp

MIDTERM EXAMINATION - CS130 - Spring 2005

Lisp Basic Example Test Questions

Artificial Intelligence Programming

Allegro CL Certification Program

Object Oriented Programming (OOP)

Extra Lecture #7: Defining Syntax

a little more on macros sort of like functions, but..

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

The Art of Lisp Programming

CSCI337 Organisation of Programming Languages LISP

1 CLWEB INTRODUCTION 1

COSI: Adding Constraints to the object-oriented paradigm

Homework #2. Source code with description. Tzewen Wang ECE578 Winter 2005

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

Object oriented programming

Symbolic Computation and Common Lisp

Lisp. Versions of LISP

Functional programming with Common Lisp

A Genetic Algorithm Implementation

Symbols are more than variables. Symbols and Property Lists. Symbols are more than variables. Symbols are more than variables.

Topic III. LISP : functions, recursion, and lists References: Chapter 3 of Concepts in programming languages by J. C. Mitchell. CUP, 2003.

Imperative, OO and Functional Languages A C program is

LFE - a lisp on the Erlang VM

Lecture #2 Kenneth W. Flynn RPI CS

Pattern Matching WIlensky Chapter 21

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

Extending Pattern Directed Inference Systems. EECS 344 Winter 2008

This should prevent residual sexism, racism, favoritism lurking in the unconscious of your professor & TA from biasing grading!!

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

Allegro CL Certification Program

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

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7

XLISP PLUS. Reference Manual. Version 3.0

Programming in QLisp. Department of Computer Science

GPS: The general problem solver. developed in 1957 by Alan Newel and Herbert Simon. (H. Simon, 1957)

(penguin-rule (if (animal-x is bird) (animal-x can swim)) (then (animal-x is penguin))) (?x is bird)

Allegro CL Certification Program

Heap storage. Dynamic allocation and stacks are generally incompatible.

Review of Functional Programming

Functional programming techniques

Chapter 1. Fundamentals of Higher Order Programming

Macroexpand-All: An Example of a Simple Lisp Code Walker

Robot Programming with Lisp

CL1 Manual. Alan Bawden ABSTRACT

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

Implementing Symmetric Multiprocessing in LispWorks

Don't Loop, Iterate MASSACHUSETTS INSTITUTE OF TECHNOLOGY ARTIFICIAL INTELLIGENCE LABORATORY. Working Paper No. 324 May, Jonathan Amsterdam

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

Putting the fun in functional programming

(defmacro for ((var start stop) &body body) (do ((,var,start (1+,var)) (limit,stop)) ((>,var

.consulting.solutions.partnership. Clojure by Example. A practical introduction to Clojure on the JVM

Code bumming for testing membership. A Lisp example

Functional Programming with Common Lisp

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Programming Languages at a Glance

Introduction to Python and Lisp

LISP - QUICK GUIDE LISP - OVERVIEW

Loading Multiple Versions of an ASDF System in the Same Lisp Image

Garbage In/Garbage SIGPLAN Out

Lisp Users and Vendors Conference. August 10, Tutorial on. Style. Peter Norvig. Sun Microsystems Labs Inc. Kent Pitman. Harlequin, Inc.

Documentation for LISP in BASIC

Introduction to Functional Programming and basic Lisp

Using a waiting protocol to separate concerns in the mutual exclusion problem

Lisp: Lab Information. Donald F. Ross

Some Useful Lisp Algorithms: Part 1

Lecture #5 Kenneth W. Flynn RPI CS

A Quick Introduction to Common Lisp

Transcription:

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 of Lisp Powerful feature, tight in the Lisp language (unlike macros in C implemented by commands of the C text preprocessor). Yet a feature that continues to set Common Lisp apart other languages. Macro is written in Lisp. When macro is compiled, it is expanded and it generates a Lisp code. After expanding the generated Lisp code is compiled and possibly evaluated. A fairly tale (fiction) of a junior programmer Mac could be said here to explain a nature of macros in Lisp

Macro Expansion Time vs. Runtime Only after all the macros have been fully expanded and the resulting code compiled the resulting program can actually be run. The time when macros run is called macro expansion time; this is distinct from runtime, when regular code, including the code generated by macros, runs. Running at macro expansion time runs in a very different environment than code running at runtime: during macro expansion time, there's no way to access the data that will exist at runtime.

Example Many existing implicit operators in Lisp are in fact macros: when: if and progn are joined together: (defmacro when (condition &rest body) `(if,condition (progn,@body))) Syntax of backquote(`): synonym for list,var :,var is replaced by the actual value of var,@body : body is assumed to be a list. @body is replaced by the elements of body.

Example, contd. (if (spam-p current-message) (progn (file-in-spam-folder current-message) (update-spam-database current-message))) (when (spam-p current-message) (file-in-spam-folder current-message) (update-spam-database current-message)) Macro when is expanded to the code above.

Examples of other standard operators which are macros in fact unless is defined: (defmacro unless (condition &rest body) `(if (not,condition) (progn,@body))) cond: (cond (test-1 form*)... (test-n form*)) setf: expanded to many variants such as setq,

Standard looping macros (dolist (var list-form) body-form*) CL-USER> (dolist (x '(1 2 3)) (print x)) 1 2 3 NIL dotimes do loop

Defining your own macros Syntax of operator defmacro (stands for DEFiniton MACRO, not for DEFinition for MAC Read Only: (defmacro name (parameter*) "Optional documentation string." body-form*) Writing macro: Write a sample call to the macro and the code it should expand into, or vice versa. Write code that generates the handwritten expansion from the arguments in the sample call.

An example of writing a macro do-primes Basic functions (here, brute-force approach): (defun primep (number) (when (> number 1) (loop for fac from 2 to (isqrt number) never (zerop (mod number fac))))) (defun next-prime (number) (loop for n from number when (primep n) return n)) The desired behaviour of our macro: (do-primes (p 0 19) (format t "~d " p))

An example of writing a macro do-primes, contd. (defmacro do-primes ((var start end) &rest body) `(do ((,var (next-prime,start) (next-prime (1+,var)))) ((>,var,end)),@body))

Debugging macros macroexpand operator macroexpand-n returns the result after the n-th run of expanding macro CL-USER> (macroexpand-1 '(do-primes (p 0 19) (format t "~d " p))) (DO ((P (NEXT-PRIME 0) (NEXT-PRIME (1+ P)))) ((> P 19)) (FORMAT T "~d " P)) T Note. DO is also macro and therefore will be expanded as well.

Another example CL-USER 53 > (defmacro from-to (from to &rest body) `(do ((x,from (+ x 1))) ((>= x,to)),@body)) FROM-TO CL-USER 54 > (from-to 1 6 (princ "."))... NIL Note: x must be an independent variable! ((let ((x 30))) (from-to 1 6 (princ ".")) NIL

gensym operator generates a unique name of an anonymous variable CL-USER 58 > (defmacro from-to (from to &rest body) (let ((x (gensym))) `(do ((,x,from (+,x 1))) ((>=,x,to)),@body))) FROM-TO CL-USER 59 > (let ((x 6)) (from-to 1 x (princ ".")))... NIL

Another using lisp macros - example Example: standard stack operations Push, Pop > (defvar SS nil) SS > (Push SS 'A) (A) > (Push SS 'B) (B A) > (Pop SS) B > SS (A) 4.15

Let's try it this way 'round... > (defun S-Push (Elm Stack) (setf Stack (cons Elm Stack))) > (defun S-Pop (Stack) (prog1 (car Stack) (setf Stack (cdr Stack)))) > (defvar SS nil) SS > (S-Push 'A SS) (A) > (S-Push 'B SS) (B) ;??? where is A > SS NIL 4.16 ;??? B disappeared as well!!? Why is it not working as expected/wanted? We should have used macros!

(defmacro Init (Stack) (list 'setf Stack nil)) (setf SS nil) (defmacro Push (Elm Stack) (list 'setf Stack (list 'cons Elm Stack) ) ) (setf SS (cons E SS)) (defmacro Pop (Stack) (list 'prog1 (list 'car Stack) (list 'setf Stack (list 'cdr Stack)) ) ) (prog1 (car SS) (setf SS (cdr SS))) 4.17

Structures

Struct - creating Macro defstruct CL-USER 8 > (defstruct node (value (progn (princ "Zadej cislo: ") (read))) (left nil) right ) NODE Macro defstruct has created: make-node (creating instances), node-p (testing type), copy-node (copying), node-value, node-left and node-right (access to the elements of the structure)

Struct CL-USER 9 > (setf nd (make-node)) Zadej cislo: 22 #S(NODE VALUE 22 LEFT NIL RIGHT NIL) CL-USER 10 > (setf nd2 (make-node :value 33 :left nil :right nil)) #S(NODE VALUE 33 LEFT NIL RIGHT NIL) CL-USER 11 > (node-p nd) T CL-USER 27 > (typep nd 'node) T CL-USER 12 > (atom nd) T CL-USER 13 > (structurep nd) T CL-USER 35 > (equalp nd (copy-node nd)) T CL-USER 36 > (equal nd (copy-node nd)) NIL CL-USER 40 > (node-value nd) 22 CL-USER 41 > (setf (node-value nd) 50) 50 CL-USER 42 > nd #S(NODE VALUE 50 LEFT NIL RIGHT NIL)

Struct Print function can be specified: CL-USER 53 > (defstruct (node (:conc-name nd) (:print-function (lambda (struct stream depth) (format stream "#uzel <hodnota: ~A, levy: ~A, pravy: ~A>" (ndvalue struct) (ndleft struct) (ndright struct))))) value (left nil) (right nil)) NODE CL-USER 66 > (setf nd1 (make-node)) #uzel <hodnota: NIL, levy: NIL, pravy: NIL> CL-USER 67 > (ndleft nd1) NIL and more