Input/Output Chapters 7 & 9. Output n Print produces output > (print 100) 100100 n It also returns...

39
Input/Output Input/Output Chapters 7 & 9 Chapters 7 & 9

Transcript of Input/Output Chapters 7 & 9. Output n Print produces output > (print 100) 100100 n It also returns...

Input/OutputInput/Output

Chapters 7 & 9Chapters 7 & 9

OutputOutput

Print produces outputPrint produces output> > (print 100)(print 100)

100100

100100 It also returns the value it printedIt also returns the value it printed

– that’s where the second 100 came fromthat’s where the second 100 came from

InputInput

Read reads & returns a formRead reads & returns a form– it does not get evaluatedit does not get evaluated

> > (read)(read)

(no evaluation at all)(no evaluation at all)

(NO EVALUATION AT ALL)(NO EVALUATION AT ALL) No variable to read into, eitherNo variable to read into, either

– use (setf use (setf var-namevar-name (read)) for that (read)) for that

Evaluating InputEvaluating Input

Eval evaluates a list as a functionEval evaluates a list as a function– works on atoms, tooworks on atoms, too

>> (eval ‘(+ 2 2)) (eval ‘(+ 2 2))

44

> > (eval (read))(eval (read))

(+ 2 2)(+ 2 2)

44

Prompted InputPrompted Input

>> (defun read-student-name (ID)(defun read-student-name (ID)(print ‘(please enter name for student id))(print ‘(please enter name for student id))(print ID)(print ID)(read))(read))

> > (read-student-name 1123)(read-student-name 1123)(PLEASE ENTER NAME FOR STUDENT ID)(PLEASE ENTER NAME FOR STUDENT ID)11231123FredFredFREDFRED

StringsStrings

For nicer outputFor nicer output– and for interaction with the O/Sand for interaction with the O/S

Double-quotes around charactersDouble-quotes around characters– sequence of characterssequence of characters

> > “This is a string”“This is a string”

““This is a string”This is a string” Case sensitive – double quotes remainCase sensitive – double quotes remain

Print Print v.v. Format Format

Print prints strings with quotesPrint prints strings with quotes Format prints strings without quotesFormat prints strings without quotes> > (and (print “This string”) (format t “This string”))(and (print “This string”) (format t “This string”))

““This string” This stringThis string” This string

NILNIL

Output from Print(includes leading newline & trailing space)

Output from Format

FormatFormat

Format returns NILFormat returns NIL 11stst argument says where to send output argument says where to send output

– t means send it to the console (monitor)t means send it to the console (monitor) 22ndnd argument is string to print argument is string to print

– must be a string – others lead to errormust be a string – others lead to error String may have String may have directivesdirectives

– to do some useful stuffto do some useful stuff

Format DirectiveFormat Directive

Format directive is command to formatFormat directive is command to format Directive starts with a tilde (~)Directive starts with a tilde (~)

– followed by optional argumentsfollowed by optional arguments– plus optional modifiers @ and :plus optional modifiers @ and :– followed by single character commandfollowed by single character command

(format t “~%”) – output an end-of-line(format t “~%”) – output an end-of-line– (format t “~5%”) – output 5 end-of-lines(format t “~5%”) – output 5 end-of-lines

The A DirectiveThe A Directive

~A (or ~a) makes format look for an ~A (or ~a) makes format look for an argument to printargument to print– argument added to format callargument added to format call– one argument for each ~a in the stringone argument for each ~a in the string

> > (format t “Student #~a is ~a~%” 1234 “Fred”)(format t “Student #~a is ~a~%” 1234 “Fred”)Student #1234 is FredStudent #1234 is FredNILNIL Note: string argument printed w/o quotesNote: string argument printed w/o quotes

ExerciseExercise

Use format with directives to re-implement Use format with directives to re-implement the read-student-name function with a better the read-student-name function with a better prompt.prompt.

> > (read-student-name 1123)(read-student-name 1123)Please enter the name for student #1123: Please enter the name for student #1123: FredFredFREDFRED

File I/OFile I/O

For I/O with files use with-open-fileFor I/O with files use with-open-file– creates a “stream” for reading or writingcreates a “stream” for reading or writing– gets attached to a filegets attached to a file– gives a name to the stream that can be used gives a name to the stream that can be used

with read, print & formatwith read, print & format

>> (with-open-file (inFile “data.txt” :direction :input) (with-open-file (inFile “data.txt” :direction :input) (read inFile))(read inFile))

(FIRST ITEM FROM “data.txt”)(FIRST ITEM FROM “data.txt”)

With-Open-FileWith-Open-File

Opens stream & closes it when doneOpens stream & closes it when done– gets closed even if there was an errorgets closed even if there was an error

11stst argument a list with: argument a list with:– name of the input stream (local variable)name of the input stream (local variable)– name of the file to attach (string)name of the file to attach (string)– :direction argument (:input, :output, …):direction argument (:input, :output, …)

22ndnd argument is executed with the file open argument is executed with the file open

File I/O FunctionsFile I/O Functions

For read, add the file stream as an argumentFor read, add the file stream as an argument– (read (read inFileinFile))

For print, dittoFor print, ditto– (print 25 (print 25 outFileoutFile))

For format, replace T with file streamFor format, replace T with file stream– (format (format outFileoutFile “Writes to the file.”) “Writes to the file.”)

File I/OFile I/O

Each with-open-file is independentEach with-open-file is independent– starts at beginning of file when readingstarts at beginning of file when reading– tries to create a new file for outputtries to create a new file for output

Can nest them to get multiple streams open Can nest them to get multiple streams open at same timeat same time

Can pass streams to functionsCan pass streams to functions– use stream parameters just like stream variablesuse stream parameters just like stream variables

ExerciseExercise

Write a function that takes a list and a Write a function that takes a list and a stream and prints each element of that list stream and prints each element of that list into that streaminto that stream

> > (with-open-stream (s “123.txt” :direction :output) (with-open-stream (s “123.txt” :direction :output) (print-to-stream ‘(one two three) s))(print-to-stream ‘(one two three) s))

onetwothree

123.txtHint:

remember mapcar& lambda

File ErrorsFile Errors

Reading from a file that doesn’t existReading from a file that doesn’t exist– with-open-file generates an errorwith-open-file generates an error

Writing to a file that Writing to a file that does does existexist– with-open-file generates an errorwith-open-file generates an error– add :if-exists :append to the 1add :if-exists :append to the 1stst argument argument

> > (with-open-file (fin “out.txt” :direction :output(with-open-file (fin “out.txt” :direction :output:if-exists :append):if-exists :append)

…)…)or :if-exists :overwrite, if you prefer

End-of-File ErrorEnd-of-File Error

Trying to reads past end-of-file is an errorTrying to reads past end-of-file is an error Unless you tell READ not toUnless you tell READ not to

– set (optional) second argument to NILset (optional) second argument to NIL

>> (with-open-file (fin “empty.txt” :direction :input) (with-open-file (fin “empty.txt” :direction :input) (read fin NIL))(read fin NIL))

NILNIL Read returns NIL when read past EOFRead returns NIL when read past EOF

End-of-File Return ValueEnd-of-File Return Value

NIL returned when read past EOFNIL returned when read past EOF But what if NIL is in your file?But what if NIL is in your file?

– will think it’s EOF before it really iswill think it’s EOF before it really is Use third argument to specify a return valueUse third argument to specify a return value

– use something that won’t be in the fileuse something that won’t be in the file

> > (read fin nil ‘EOF)(read fin nil ‘EOF)

EOFEOFRead returns this value when it reaches the end of file

Reading to End-of-FileReading to End-of-File

Need indefinite iterationNeed indefinite iteration– to specify when to stopto specify when to stop

Do special formDo special form– (do <variable-list> <test-return> <body>)(do <variable-list> <test-return> <body>)

>> (with-open-file (fin “data.txt” :direction :input)(with-open-file (fin “data.txt” :direction :input)(do ((count –1 (+ count 1)) (term NIL))(do ((count –1 (+ count 1)) (term NIL))

((eql term ‘eof) count)((eql term ‘eof) count)(setf term (read fin nil ‘eof))))(setf term (read fin nil ‘eof))))

Do Special FormDo Special Form

Variable list, each one:Variable list, each one:– variable name, initial value, update valuevariable name, initial value, update value

Test-returnTest-return– stop the loop when the test is truestop the loop when the test is true– value to return (evaluated after test succeeds)value to return (evaluated after test succeeds)

BodyBody– executed once per iterationexecuted once per iteration

Example (Empty File)Example (Empty File)

(do (do ((count –1((count –1 (+ count 1) (+ count 1)) (term NIL))) (term NIL))((eql term ‘eof) count)((eql term ‘eof) count)

(setf term (read fin nil ‘eof))))(setf term (read fin nil ‘eof)))) countcount initialized to –1 & initialized to –1 & termterm to NIL to NIL termterm not eql EOF not eql EOF termterm set to EOF (nothing in the file to read) set to EOF (nothing in the file to read) countcount updated to updated to countcount + 1 = 0 + 1 = 0 termterm eql EOF eql EOF return return countcount 0 0

Example (Empty File)Example (Empty File)

(do ((count –1 (+ count 1)) (term NIL))(do ((count –1 (+ count 1)) (term NIL))((eql term ‘eof)((eql term ‘eof) count count))

(setf term (read fin nil ‘eof))))(setf term (read fin nil ‘eof)))) countcount initialized to –1 & initialized to –1 & termterm to NIL to NIL termterm not eql EOF not eql EOF termterm set to EOF (nothing in the file to read) set to EOF (nothing in the file to read) countcount updated to updated to countcount + 1 = 0 + 1 = 0 termterm eql EOF eql EOF return return countcount 0 0

Example (Empty File)Example (Empty File)

(do ((count –1 (+ count 1)) (term NIL))(do ((count –1 (+ count 1)) (term NIL))((eql term ‘eof) count)((eql term ‘eof) count)

(setf term (read fin nil ‘eof))(setf term (read fin nil ‘eof)))))) countcount initialized to –1 & initialized to –1 & termterm to NIL to NIL termterm not eql EOF not eql EOF termterm set to EOF (nothing in the file to read) set to EOF (nothing in the file to read) countcount updated to updated to countcount + 1 = 0 + 1 = 0 termterm eql EOF eql EOF return return countcount 0 0

Example (Empty File)Example (Empty File)

(do ((do ((count (count –1 –1 (+ count 1))(+ count 1)) (term NIL)) (term NIL))((eql term ‘eof) count)((eql term ‘eof) count)

(setf term (read fin nil ‘eof))))(setf term (read fin nil ‘eof)))) countcount initialized to –1 & initialized to –1 & termterm to NIL to NIL termterm not eql EOF not eql EOF termterm set to EOF (nothing in the file to read) set to EOF (nothing in the file to read) countcount updated to updated to countcount + 1 = 0 + 1 = 0 termterm eql EOF eql EOF return return countcount 0 0

Example (Empty File)Example (Empty File)

(do ((count –1 (+ count 1)) (term NIL))(do ((count –1 (+ count 1)) (term NIL))((eql term ‘eof) count)((eql term ‘eof) count)

(setf term (read fin nil ‘eof))))(setf term (read fin nil ‘eof)))) countcount initialized to –1 & initialized to –1 & termterm to NIL to NIL termterm not eql EOF not eql EOF termterm set to EOF (nothing in the file to read) set to EOF (nothing in the file to read) countcount updated to updated to countcount + 1 = 0 + 1 = 0 termterm eql EOF eql EOF return return countcount 0 0

Example (Empty File)Example (Empty File)

(do ((count –1 (+ count 1))(do ((count –1 (+ count 1)) (term NIL (read fin nil ‘eof)))(term NIL (read fin nil ‘eof)))((eql term ‘eof) count))((eql term ‘eof) count))

countcount initialized to –1 & initialized to –1 & termterm to NIL to NIL termterm not eql EOF not eql EOF countcount updated to updated to countcount + 1 = 0, + 1 = 0, termterm

updated to EOF (nothing in the file to read)updated to EOF (nothing in the file to read) termterm eql EOF eql EOF return return countcount 0 0

Do Do vs.vs. For For

(do ((do ((i 10 (– i 1))(i 10 (– i 1))))

(((<= i 0)(<= i 0) result) result)

<body><body>))

(do ((do ((i 1 (+ i 1)(i 1 (+ i 1)))

(j 1 (* j 2))(j 1 (* j 2))))

(((> i 10)(> i 10) result) result)

<body><body>))

for for (i=10;(i=10; i>0;i>0; i–i– ––))

<body>;<body>;

return result;return result;

for (for (i=1, j=1;i=1, j=1; i <= 10;i <= 10;

i++, j*=2i++, j*=2))

<body>;<body>;

return result;return result;

Read to EOF, Standard FormRead to EOF, Standard Form

fread(fin, n)fread(fin, n);;

while (fin) {while (fin) {

<process>;<process>;

fread(fin, n)fread(fin, n);;

}}

(do ((n (do ((n (read fin NIL)(read fin NIL) (read fin NIL)(read fin NIL)))))

((not n) ((not n) resultresult))

<process>)<process>)

Read initial valueRead initial value– update by reading another valueupdate by reading another value

Same as for imperativeSame as for imperative

ExerciseExercise

Write a function that reads each element Write a function that reads each element from the file “lists.txt” and prints the first from the file “lists.txt” and prints the first element of each list into file “firsts.txt”element of each list into file “firsts.txt”– overwrite previous “firsts.txt”, if it existsoverwrite previous “firsts.txt”, if it exists

(one two three)(a b c)(do re mi)

oneado

lists.txt firsts.txt

(lists-to-firsts)

Character InputCharacter Input

Read-char reads a single characterRead-char reads a single character Read-line reads until the next end-of-lineRead-line reads until the next end-of-line

– returns a stringreturns a string Both use same extra arguments as readBoth use same extra arguments as read> > (list (read-char) (read-line))(list (read-char) (read-line))

This is my inputThis is my input

(#\T “his is my input”)(#\T “his is my input”)

CharactersCharacters

Single characters printed with #\ in frontSingle characters printed with #\ in front– #\Y is the character capital Y#\Y is the character capital Y– #\* is the character asterisk#\* is the character asterisk

Special characters have namesSpecial characters have names– #\Space is the space character#\Space is the space character– #\Newline & #\Tab likewise#\Newline & #\Tab likewise– #\Asterisk = #\*#\Asterisk = #\*

Character EqualityCharacter Equality

Characters are equal only if same caseCharacters are equal only if same case Char-equal does case-insensitive compareChar-equal does case-insensitive compare> > (equal #\A #\A)(equal #\A #\A)

TT

> > (equal #\a #\A)(equal #\a #\A)

NILNIL

> > (char-equal #\a #\A)(char-equal #\a #\A)

TT

String EqualityString Equality

Strings are equal only if same caseStrings are equal only if same case String-equal does case-insensitive compareString-equal does case-insensitive compare> > (equal “ABC” “ABC”)(equal “ABC” “ABC”)

TT

> > (equal “abc” “ABC”)(equal “abc” “ABC”)

NILNIL

> > (string-equal “abc” “ABC”)(string-equal “abc” “ABC”)

TT

SubstringsSubstrings

Search looks for substringSearch looks for substring– returns position of substring (0 = 1returns position of substring (0 = 1stst position) position)– returns NIL if it’s not therereturns NIL if it’s not there– (search “abc” “abcdef”)(search “abc” “abcdef”) => 0 => 0– (search “cde” “abcdef”)(search “cde” “abcdef”) => 2 => 2– (search “fgh” “abcdef”)(search “fgh” “abcdef”) => NIL => NIL– (search “BC” “abcdef”)(search “BC” “abcdef”) => NIL => NIL– (search “BC” “abcdef” :test #’char-equal)(search “BC” “abcdef” :test #’char-equal) => 1 => 1

Converting to StringConverting to String

Search requires string argumentsSearch requires string arguments– won’t find a character in a stringwon’t find a character in a string

Convert character to string using stringConvert character to string using string(search (string #\d) “bad dog”)(search (string #\d) “bad dog”) => 2 => 2

String also works on atomsString also works on atoms(string ‘fred)(string ‘fred) => “FRED” => “FRED”– doesn’t work on listsdoesn’t work on lists

Strings & ListsStrings & Lists

Many list functions work on stringsMany list functions work on strings– (length “abc”) => 3(length “abc”) => 3– (reverse “abcd”) => “dcba”(reverse “abcd”) => “dcba”– (elt “abcd” 1) => b(elt “abcd” 1) => b

Nth works on lists, but not stringsNth works on lists, but not strings– (nth 1 ‘(a b c d)) => b(nth 1 ‘(a b c d)) => b– (nth 1 “abcd”) => ERROR(nth 1 “abcd”) => ERROR

ExerciseExercise

Write a function that scans a text file & Write a function that scans a text file & prints out the lines containing the string prints out the lines containing the string “his” (or “His”, or “HIS”, …)“his” (or “His”, or “HIS”, …)– the the namename of the text file is given of the text file is given– prefix each line printed with its line numberprefix each line printed with its line number

Hello.I’m writing to tell youhis story.This may take a while.

3: his story.4: This may take a while.

(scan-for-his “input.txt”)

inpu

t.txt

Next TimeNext Time

Midterm testMidterm test

Next TuesdayNext Tuesday– Repetition controls in LISPRepetition controls in LISP