06 INPUT AND OUTPUT Functional Programming. Streams Two kinds of streams  Character streams  Binary streams Character streams are Lisp objects representing.

Slides:



Advertisements
Similar presentations
Lisp Control and Data Structures CIS 479/579 Bruce R. Maxim UM-Dearborn.
Advertisements

09 Examples Functional Programming. Tower of Hanoi AB C.
ANSI Common Lisp 3. Lists 20 June Lists Conses List Functions Trees Sets Stacks Dotted Lists Assoc-lists.
ANSI Common Lisp 5. Control 16 June Blocks -- progn progn > (progn (format t “a”) (format t “b”) ( )) ab 23 The expressions within its body.
Lisp Recitation (cse471/598 Fall 2007 ) Aravind Kalavagattu.
CSE 341, S. Tanimoto Pattern Matching - 1 Pattern Matching in Lisp Lists can be used to represent sentences, relations, tree structures, etc. (this list.
Interactive Session on Project 2 & Assorted Topics Copyright, 1996 © Dale Carnegie & Associates, Inc. By Surendra Singhi Spring 2005.
Common Lisp! John Paxton Montana State University Summer 2003.
Project 1: Background Informed search : 8- puzzle world BFS, DFS and A* algorithms Heuristics : Manhattan distance, Number of misplaced tiles Lisp programming.
CSCI Programming in Lisp; Instructor: Alok Mehta; 3_structs.ppt1 CSCI 2210: Programming in Lisp Programming Techniques Data Structures More Built-in.
First Lecture on Introductory Lisp Yun Peng. Why Lisp? Because it’s the most widely used AI programming language Because AI researchers and theoreticians.
CMSC 471 LISP. Why Lisp? Because it’s the most widely used AI programming language Because it’s good for writing production software (Graham article)
ANSI Common Lisp 4. Specialized Data Structures 7 June 2003.
It is suggested that you use the Lisp interpreter available on the general machine (general.asu.edu). You are welcome to use other interpreters while developing,
LISP A brief overview. Lisp stands for “LISt Process” –Invented by John McCarthy (1958) –Simple data structure (atoms and lists) –Heavy use of recursion.
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.
F UNCTIONAL P ROGRAMMING 05 Functions. F UNCTIONS - G LOBAL F UNCTIONS fboundp Tells whether there is a function with a given symbol as its name > (fboundp.
Allegro CL Certification Program Lisp Programming Series Level I Session Top Ten Things to Know.
Yu-Tzu Lin ( 林育慈 )
Advanced Functions In CL, functions are often supplied as parameters to other functions –This gives us tremendous flexibility in writing functions whose.
Functional Programming
Functional Programming 02 Lists
Input/Output Chapters 7 & 9. Output n Print produces output > (print 100) n It also returns the value it printed –that’s where the second 100 came.
Mitthögskolan 10/8/ Common Lisp LISTS. Mitthögskolan 10/8/2015 2Lists n Lists are one of the fundamental data structures in Lisp. n However, it.
For Monday Read Chapter 3 Homework: –Lisp handout 2.
1 Lisp Functions –Built-in functions –Defining functions –Function Evaluation and Special Forms defun, if Control statements –Conditional if, cond –Repetition.
Lecture 2-1CS250: Intro to AI/Lisp Intelligent Agents Lecture 3-2 October 14 th, 1999 CS250.
1 More About Lisp. 2 Functions on Lists (setf x '(a b c)) => (A B C) (setf y '(1 2 3)) => (1 2 3) (rest x) => (B C) ;;all but the first element (nth 1.
Functional Programming and Lisp. Overview In a functional programming language, functions are first class objects. In a functional programming language,
04 Control. Control-Blocks Common Lisp has 3 basic operators for creating blocks of code progn block tagbody If ordinary function calls are the leaves.
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.
Lecture 6-2CS250: Intro to AI/Lisp Programming in Your Favorite Language Lecture 5-2 February 11 th, 1999 CS250.
PRACTICAL COMMON LISP Peter Seibel 1.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Macros “How can you get anything done in [other languages], I think, without macros?” - Paul Graham, 2003.
Lisp Files, Arrays, and Macros CIS 479/579 Bruce R. Maxim UM-Dearborn.
Chapter 13 – C++ String Class. String objects u Do not need to specify size of string object –C++ keeps track of size of text –C++ expands memory region.
Introduction to ACL2 CS 680 Formal Methods for Computer Verification Jeremy Johnson Drexel University.
More Language Features Functional Programming Academic Year Alessandro Cimatti
1 Chapter 2 C++ Syntax and Semantics, and the Program Development Process.
Introduction to LISP. Lisp Extensible: It lets you define new operators yourself Lisp programs are expressed as lisp data structures –You can write programs.
11 Speed & Debug.  Lisp is really two languages:  A language for writing fast programs  A language for writing programs fast  In the early stage,
UMBC CMSC Common Lisp II. UMBC CMSC Input and Output Print is the most primitive output function > (print (list 'foo 'bar)) (FOO BAR) The.
C++ String Class nalhareqi©2012. string u The string is any sequence of characters u To use strings, you need to include the header u The string is one.
Milos Hauskrecht (PDF) Hieu D. Vu (PPT) LISP PROGARMMING LANGUAGE.
1 Variable Declarations Global and special variables – (defvar …) – (defparameter …) – (defconstant …) – (setq var2 (list 4 5)) – (setf …) Local variables.
Basic Introduction to Lisp
Control Structures CSC 358/ Outline Midterm Lab #3 Homework #4 Sequential structures Conditional structures Unconditional branching Iteration.
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.
1 Common Lisp. 2 Lisp stands for “LISt Process” –Invented by John McCarthy (1958) –Simple data structure (atoms and lists) –Heavy use of recursion –Interpretive.
Input Streams “A program designed for inputs from people is usually stressed beyond the breaking point by computer-generated inputs.” Dennis Ritchie, Bell.
 If you want to open an already existing file select file->open on the menu and then choose the program you want to modify. If you want to open a new.
1 Outline Review Introduction to LISP Symbols and Numbers Lists Writing LISP Functions LISPWorks.
Section 15.4, 15.6 plus other materials
Intelligent Agents Lecture 3-2 October 14th, 1999 CS250 Lecture 2-1
Getting Started with Lisp
LISP A brief overview.
“The fastest I/O is no I/O.” Nils-Peter Nelson, Bell Labs
First Lecture on Introductory Lisp
J.E. Spragg Mitthögskolan 1997
Imperative Data Structures
Modern Programming Languages Lecture 21 Fakhar Lodhi
Modern Programming Languages Lecture 20 Fakhar Lodhi
LISP A brief overview.
Peter Seibel Practical Common Lisp Peter Seibel
Abstraction and Repetition
Data Structures in Lisp
Common Lisp II.
Presentation transcript:

06 INPUT AND OUTPUT Functional Programming

Streams Two kinds of streams  Character streams  Binary streams Character streams are Lisp objects representing sources and/or destinations of characters To read from or write to a file, you open it as a stream, but streams are not identical with files When you read or print at the toplevel, you also use a stream

Streams Default input is read from the stream *standard-input* Default output is write to *standard-output* Initially *standard-input* and *standard-output* will be the same place: a stream presenting the toplevel

Streams Make the file  > (setf path (make-pathname :name “myfile”)) #P”myfile” Open the file  > (setf str (open path :direction :output :if-exists :supersede)) # Write to the stream  > (format str “Something~%”) NIL Close the stream  > (close str) NIL

Streams Read the file  Open a stream with :direction :input  > (setf str (open path :direction :input)) #  > (read-line str) “Something” with-open-file macro  > (with-open-file (str path :direction :output :if-exists :supersede) (format str “Something~%”))  The stream is automatically closed

Input Most popular input functions  read-line  read > (progn (format t “Please enter your name: “) (read-line)) Please enter your name: Rodrigo de Bivar “Rodrigo de Bivar” NIL → is true only if read-line ran out of input before encountering a newline

Input (defun pseudo-cat (file) (with-open-file (str file :direction :input) (do ((line (read-line str nil ‘eof) (read-line str nil ‘eof))) ((eql line ‘eof)) (format t “~A~%” line)))) If you want input parsed into Lisp objects, use read  > (read) (a b c) (A B C)

Output Three simplest output functions  prin1  Generates output for programs  > (prin1 “Hello”) “Hello” “Hello”  princ  Generates output for people  > (princ “Hello”) Hello “Hello”  terpri  Prints a new line

Output format  > (format nil “Dear ~A, ~% Our records indicate…” “Mr. Malatesta”) “Dear Mr. Malatesta, Our records indicate…”  > (format t “~S ~A” “z” “z”) “z” z NIL

Output > (format nil “~10,2,0,’*, ‘ F” ) “ 26.22” Rounded to 2 decimal places With the decimal point shifted right 0 places Right-justified in a field of 10 characters Padded on the left by blanks If it is too long to fit in the space allowed by the first argument, the character * is printed > (format nil “~,2,,,F” ) “26.22” > (format nil “~,2F” ) “26.22”

Review – Function pointer in C 1#include 2 3using namespace std; 4 5void printArrayOdd(int* beg, int* end) { 6 while(beg != end) { 7 if ((*beg)%2) 8 cout << *beg << endl; 9 10 beg++; 11 } 12} 13 14void printArrayEven(int* beg, int* end) { 15 while(beg != end) { 16 if (!((*beg)%2)) 17 cout << *beg << endl; beg++; 20 } 21} 22

Review – Function pointer in C 23void printArrayGreaterThan2(int* beg, int* end) { 24 while(beg != end) { 25 if ((*beg)>2) 26 cout << *beg << endl; beg++; 29 } 30} 31 32int main() { 33 int ia[] = {1, 2, 3}; cout << "Odd" << endl; 36 printArrayOdd(ia, ia + 3); cout << "Even" << endl; 40 printArrayEven(ia, ia + 3); cout << "Greater than 2" << endl; 43 printArrayGreaterThan2(ia, ia + 3); 44} Execution results Odd 1 3 Even 2 Greater than 2 3

Review – Function pointer in C 1/**//* 2 (C) OOMusou Filename : FuntionPointer.cpp 5Compiler : Visual C / BCB 6.0 / gcc / ISO C++ 6Description : Demo how to use function pointer 7Release : 05/01/ */ 9#include 10 11using namespace std; 12 13typedef bool (*predicate)(int); 14 15bool isOdd(int i) { 16 return i%2? true : false; 17} 18 19bool isEven(int i) { 20 return i%2? false : true; 21} 22

Review – Function pointer in C 23bool greaterThan2(int i) { 24 return i > 2; 25} 26 27void printArray(int* beg, int* end, predicate fn) { 28 while(beg != end) { 29 if ((*fn)(*beg)) 30 cout << *beg << endl; beg++; 33 } 34} 35 36int main() { 37 int ia[] = {1, 2, 3}; cout << "Odd" << endl; 40 printArray(ia, ia + 3, isOdd); cout << "Even" << endl; 43 printArray(ia, ia + 3, isEven); cout << "Greater than 2" << endl; 46 printArray(ia, ia + 3, greaterThan2); 47} Execution results Odd 1 3 Even 2 Greater than 2 3

Review – Function pointer in C By using function pointer, C can pass a function as an argument to another function C++ and C# also provide similar idea  C++: Function object (Functor)  C# (pronounced as C sharp): Delegate But…., how to return a function?  C also could return a function pointer   However, it needs more complex consideration to write such a function with higher feasibility

Review – Closure Functional programming languages use “closures” to provide feasibility of functions, so that returning a function becomes easier and more practical (defun make-adder (n) #’(lambda (x) (+ x n))) → returns a function  (setf add3 (make-adder 3)) #  > (funcall add3 2) 5

Review > (list ‘my (+ 2 1) “Sons”) (MY 3 “Sons”) > (list ‘(+ 2 1) (+ 2 1)) ((+ 2 1) 3) > (cons ‘a ‘(b c d)) (A B C D) > (cons ‘a (cons ‘b nil)) (A B) > (car ‘(a b c)) A > (cdr ‘(a b c)) (B C)

Review > (setf x (list ‘a ‘b ‘c)) (A B C) > (setf (car x ) ‘n) N > x (N B C)

Review > (apply #’+ ‘(1 2 3)) 6 > (mapcar #’(lambda (x) (+ x 10)) ‘(1 2 3)) ( ) > (mapcar #’list ‘(a b c) ‘( )) ((A 1) (B 2) (C 3)) > (maplist #’(lambda (x) x) ‘(a b c)) ((A B C) (B C) (C))

Review > (member ‘b ‘(a b c)) (B C) > (member ‘(b) ‘((a) (b) (c))) NIL Why? Equal: the same expression? Eql: the same symbol or number? member compares objects using eql > (member ‘(a) ‘((a) (z)) :test #’equal) ;:test-> keyword argument ((A) (Z)) > (member ‘a ‘((a b) (c d)) :key #’car) ((A B) (C D))  Ask if there is an element whose car is a

Review > (subseq ‘(a b c d) 1 2) (B) > (every #’oddp ‘(1 3 5)) ;everyone is … T > (some #’evenp ‘(1 2 3)) ;someone is … T > (every #’> ‘(1 3 5) ‘(0 2 4)) T

Review Dotted list: is an n-part data structure  (A. B)  (setf pair (cons ‘a ‘b)) (A. B) > ‘(a. (b. (c. nil))) (A B C) > (cons ‘a (cons ‘b (cons ‘c ‘d))) (A B C. D)

Review make-array  > (setf arr (make-array ‘(2 3) :initial-element nil)) #  Maximum:  7 dimensions  Each dimension can have 1023 elements  Initial-element  Optional  Whole array will be initialized to this value  > (aref arr 0 0) NIL  > (setf (aref arr 0 0) ‘b) B  > (aref arr 0 0) ; access the array B

Review One-dimensional array  > (setf vec (make-array 4 :initial-element nil)) #(NIL NIL NIL NIL)  > (vector “a” ‘b 5 “c”) #(“a” B 5 “c”)  > (setf vec (vector “a” ‘b 5 “c”)) > (svref vec 1) ;access the vector (sv: simple vector) B String: a vector of characters > (sort “elbow” #’char<) “below” Retrieve an element of a string  > (aref “abc” 1) #\b  > (char “abc” 1) #\b

Review Replace elements of a stirng  > (let ((str (copy-seq “Merlin”))) (setf (char str 3) #\k) str) “Merkin” Compare two strings  > (equal “fred” “fred”) T  > (equal “fred” “Fred”) NIL  > (string-equal “fred” “Fred”) T Building strings  > (format nil “~A or ~A” “truth” “dare”) “truth or dare”  > (concatenate ‘string “not “ “to worry”) “not to worry”

Review > (progn (format t “a”) (format t “b”) ( ) ) ab 23 -> only the value of the last expression is returned > (block head (format t “Here we go.”) (return-from head ‘idea) (format t “We’ll never see this.”)) Here we go.

Review > (let ((x 7) (y 2)) (format t “Number”) (+ x y)) Number 9 > ((lambda (x) (+ x 1)) 3) 4 (let ((x 2) (y (+ x 1))) (+ x y)) ((lambda (x y) (+ x y)) 2 (+ x 1))

Review (if ) (if )  (when ) (if nil )  (unless )

Review cond (cond ( …) ( …) … ( …) );cond case (case ( …) ( …)... ( …) ) ;case

Review do (do (( ) ( ) … ( )) ( ) ) ;do > (let ((x ‘a)) (do ((x 1 (+ x 1)) (y x x)) ((> x 5)) (format t “(~A ~A) “ x y))) (1 A) (2 1) (3 2) (4 3) (5 4) ;on each iteration, x gets its previous NIL ;value plus 1; y also gets the previous ;value

Review do*  Has the same relation to do as let* does to let  > (do* ((x 1 (+ x 1)) (y x x)) ((> x 5)) (format t “(~A ~A) “ x y)) (1 1) (2 2) (3 3) (4 4) (5 5) NIL

Review dolist  > (dolist (x ‘(a b c d) ‘done) (format t “~A “ x)) A B C D DONE dotimes  > (dotimes (x 5 x) ; for x = 0 to 5-1, return x (format t “~A “ x))

Review Multiple values > (values ‘a nil (+ 2 4)) A NIL 6 (labels ((add10 (x) (+ x 10)) (consa (x) (cons ‘a x))) (consa (add10 3))) (A. 13) > (labels ((len (lst) (if (null lst) 0 (+ (len (cdr lst)) 1)))) (len ‘(a b c))) 3

Review (defun our-funcall (fn &rest args) (apply fn args)) > (defun keylist (a &key x y z) (list a x y z))

Review (defun disjoin (fn &rest fns) (if (null fns) fn (let ((disj (apply #’disjoin fns))) #’(lambda (&rest args) (or (apply fn args) (apply disj args)))))) > (mapcar (disjoin #’integerp #’symbolp) ‘(a “a” 2 3)) (T NIL T T)

Midterm exam  Time: April 21  Classroom: 資工所 ( 應用科學大樓 )/B1 演講廳