FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 3. LISP: ZÁKLADNÍ FUNKCE, POUŽÍVÁNÍ REKURZE,

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

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Í 5. LISP: MAKRA, DATOVÁ STRUKTURA ZÁZNAM

Recursion & Iteration

Artificial Intelligence Programming

Lisp. Versions of LISP

Building a system for symbolic differentiation

Introduction to Scheme

Imperative, OO and Functional Languages A C program is

A Brief Introduction to Scheme (II)

Using Symbols in Expressions (1) evaluate sub-expressions... Number. ( ) machine code to add

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Lecture Notes on Lisp A Brief Introduction

Functional programming with Common Lisp

Building a system for symbolic differentiation

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define

Lisp Basic Example Test Questions

SCHEME 10 COMPUTER SCIENCE 61A. July 26, Warm Up: Conditional Expressions. 1. What does Scheme print? scm> (if (or #t (/ 1 0)) 1 (/ 1 0))

Lecture #2 Kenneth W. Flynn RPI CS

An Explicit-Continuation Metacircular Evaluator

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003

Lists in Lisp and Scheme

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

CS 314 Principles of Programming Languages


Common LISP Tutorial 1 (Basic)

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives

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

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

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

Tail Recursion and Accumulators

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015

6.034 Artificial Intelligence February 9, 2007 Recitation # 1. (b) Draw the tree structure corresponding to the following list.

Common Lisp. Blake McBride

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

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

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4

Problems 3-1, 3.3, 3.4 and 3.5 in Chapter 3 of Winston and Horn's LISP (see Below)

Midterm Examination (Sample Solutions), Cmput 325

Chapter 1. Fundamentals of Higher Order Programming

CSCI337 Organisation of Programming Languages LISP

Introduction to Functional Programming

Putting the fun in functional programming

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

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

A little bit of Lisp

Essentials of Programming Languages Language

Essentials of Programming Languages Language

;; definition of function, fun, that adds 7 to the input (define fun (lambda (x) (+ x 7)))

CS450 - Structure of Higher Level Languages

Introduction to ACL2. CS 680 Formal Methods for Computer Verification. Jeremy Johnson Drexel University

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives

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

Lecture #24: Programming Languages and Programs

Functional Programming. Pure Functional Programming

Lisp: Question 1. Dr. Zoran Duric () Midterm Review 1 1/ 13 September 23, / 13

A Genetic Algorithm Implementation

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017

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

A Quick Introduction to Common Lisp

Functional Programming. Pure Functional Languages

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

Look at the outermost list first, evaluate each of its arguments, and use the results as arguments to the outermost operator.

Common LISP-Introduction

Heap storage. Dynamic allocation and stacks are generally incompatible.

Functional Programming. Contents

ALISP interpreter in Awk

CS 314 Principles of Programming Languages. Lecture 16

Review of Functional Programming

Lambda Calculus see notes on Lambda Calculus

Streams and Evalutation Strategies

Deferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.

User-defined Functions. Conditional Expressions in Scheme

Functional Programming. Pure Functional Languages

Documentation for LISP in BASIC

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

Below are example solutions for each of the questions. These are not the only possible answers, but they are the most common ones.

Gene Kim 9/9/2016 CSC 2/444 Lisp Tutorial

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives

Associative Database Managment WIlensky Chapter 22

Associative Database Managment

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

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

SCHEME AND CALCULATOR 5b

YOUR NAME PLEASE: *** SOLUTIONS ***

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters.

MORE SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

Fifth Generation CS 4100 LISP. What do we need? Example LISP Program 11/13/13. Chapter 9: List Processing: LISP. Central Idea: Function Application

HIERARCHICAL DATA What is a Tree? How is it different from a Deep List? When would you use one over the other?

;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for

CSc 520. Principles of Programming Languages 7: Scheme List Processing

CMSC 331 Final Exam Section 0201 December 18, 2000

INF4820. Common Lisp: Closures and Macros

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012

CS 61A, Fall, 2002, Midterm #2, L. Rowe. 1. (10 points, 1 point each part) Consider the following five box-and-arrow diagrams.

CSc 520 Principles of Programming Languages. Examining Lists. Constructing Lists... 7: Scheme List Processing

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

1.3. Conditional expressions To express case distinctions like

LECTURE 16. Functional Programming


Transcription:

FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 3. LISP: ZÁKLADNÍ FUNKCE, POUŽÍVÁNÍ REKURZE, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší budoucnosti

Comments in Lisp ; comments aligned to the same line ;; aligned for the next line and outside functions ;;; comments of headings of functions ;;;; comments of major sections, files

Condition expressions = equal eq eql equality of numbers structural isomorphism (same values) both arguments the same in memory identical objects for numbers their values are compared; for structural objects their memory position are compared and, or logical and, or

More predicates (null s) T for an empty list (symbol s) T for atomic symbols (number s) T for numbers s (consp s) T for cons value s (i.e. it has car and cdr) (listp s) T for list s (maybe empty)

Selectors/accessors cxx...xr selectors - combinations of car/cdr (caar x) = (car (car x)) (cadr x) = (car (cdr x))... Similarly caaar, caadr,..., cdddr, caaaar, caaadr,..., cddddr (length s) how many elements in s (nth n s) n-th element of list s (leftmost is 0th!) (nthcdr n s) n-th cdr (last s) last cons cell (butlast s) list s without the last element (butlast s n) n elements from the end removed

Standard, but could be defined: (defun nth (N S) ; N-th element of list S (cond ((= N 0) (car S)) ; car is 0th! (T (nth (1- N) (cdr S))) ) ) (defun nthcdr (N S) ; n-th cdr (cond ((= N 0) S) (T (nthcdr (1- N) (cdr S))) ) ) (defun last (S) (cond ((null S) NIL) ((null (cdr S) S) (T (last (cdr S))) ) ) ; the last cons cell (defun butlast (S) ; list S without the last element (cond ((or (null S) (null (cdr S)) NIL) (T (cons (car S) (butlast (cdr S)) ) ) ) )

More functions (member Elm Lst) looks for Elm in Lst, returns the part starting with Elm (remove Elm Lst) deletes Elm from Lst (returns a copy) (subst New Old Lst) substitutes New for Old in Lst (returns a copy) (nsubst New Old Lst) substitutes New for Old in Lst (returns a modified Lst) (reverse Lst) reverses Lst (returns a fresh list)

Again, they could be defined: (defun member (Elm Lst) (cond ((null Lst) NIL) ((eql Elm (car Lst)) Lst) ; eq, eql, equal... (T (member Elm (cdr Lst))) ) ) (defun remove (Elm Lst) (cond ((null Lst) NIL) ((eql Elm (car Lst)) ; Elm found? (remove Elm (cdr Lst))) ; remove from rest (T (cons (car Lst) ; else copy car (remove Elm (cdr Lst))) ) ) (defun subst (New Old Lst) (cond ((null Lst) NIL) ((eql Old (car Lst)) (cons New (subst New Old (cdr Lst)))) (T (cons (car Lst) (subst New Old (cdr Lst)))) ) ) ; what about substitution in all levels???

Again, they could be defined: (defun nsubst (New Old Lst) ; a modifying substitution (cond ((null Lst) NIL) ((eql Old (car Lst)) (setf (car Lst) New) (setf (cdr Lst) (nsubst New Old (cdr Lst))) Lst) (T (setf (cdr Lst) (nsubst New Old (cdr Lst))) Lst) ) ) ; calls for some improvement... ;; How do we reverse a list??? Recursion classics (defun reverse (Lst) (if (null Lst) NIL (append (reverse (cdr Lst)) (list (car Lst))))) (defun append (X Y) (if (null X) Y (cons (car X) (append (cdr X) Y))))

Again, they could be defined: ;; Can we do reverse any better??? (defun reverse (Lst) (rev-iter Lst Nil)) (defun rev-iter (Lst Acc) ;tail-recursive version (if (null Lst) Acc (rev-iter (cdr Lst) (cons (car Lst) Acc))))

Computation: CL-USER 1 > (rev S) 0 REV >... >> LST : (A B C) 1 REV-ITER >... >> LST : (A B C) >> ACC : NIL 2 REV-ITER >... >> LST : (B C) >> ACC : (A) 3 REV-ITER >... >> LST : (C) >> ACC : (B A) 4 REV-ITER >... >> LST : NIL >> ACC : (C B A) 4 REV-ITER <... << VALUE-0 : (C B A) 3 REV-ITER <... << VALUE-0 : (C B A) 2 REV-ITER <... << VALUE-0 : (C B A) 1 REV-ITER <... << VALUE-0 : (C B A) 0 REV <... << VALUE-0 : (C B A)

In a simplified presentation: (rev (A B C)) (rev-iter (A B C) () ) (rev-iter (B C) (A) ) (rev-iter (C) (B A) ) (rev-iter () (C B A) ) (C B A) returned (C B A) returned (C B A) returned (C B A) returned (C B A) returned (C B A) 2.12

Recursion General rule of recursive design 1. first test for trivial cases (such as 0, 1, NIL, atom,... ) 2. then develop branches with recursive calls in which the procedure is applied to reduced arguments (such as (1- N), (cdr S),... ) Important note: recursion is implemented with the use of pushdown store (stack) data structure.

A simple example ;;; copying a list (the highest level only) (defun Copy (S) (if (null S) NIL (cons (car S) (Copy (cdr S))) )) ;;; Now copying at all levels (defun CopyAll (S) (cond ((null S) nil) ((atom S) S) ; remember this case!! ((cons (CopyAll (car S)) (CopyAll (cdr S)))) ))

Taxonomy of recursion nested recursion (defun Ack (m n) ;(Ack 4 5) stack overflow (exponential) (cond ((zerop m) (1+ n)) ((zerop n) (Ack (1- m) 1)) (T (Ack (1- m) (Ack m (1- n)))) )) tree recursion (defun Fib (n) ; (Fib 35) took 26.328 s (if (< n 2) n (+ (Fib (- n 1)) (Fib (- n 2))) ) )

Taxonomy of recursion linear recursion ;; just one recursive call (defun linlen (s) (if (null s) 0 (1+ (linlen (cdr s))) ) ) tail recursion (defun trlen (s) (taillen s 0)) ;; one recursive call, no pending operations (defun taillen (s acc) (if (null s) acc (taillen (cdr s) (1+ acc)) ) )

Tail recursion nothing to do after the function returns except returning its value the most efficient type of recursion from the implementation point of view: Saving a new stack frame for each recursive call is a waste! The current stack frame can be reused. (All better compilers of functional languages always do tail-recursion optimisation.) can be mechanically transformed into explicit iteration

Semestral homework An introduction to your semestral homework should be presented during the third lecture.