Scheme: Strings Scheme: I/O

Similar documents
Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G.

Scheme: Expressions & Procedures

A Brief Introduction to Scheme (II)

Haskell: Lists. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Friday, February 24, Glenn G.

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

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

User-defined Functions. Conditional Expressions in Scheme

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am.

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

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

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

Functional Programming. Pure Functional Languages

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages. Lecture 16

Project 2: Scheme Interpreter

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

CSCI337 Organisation of Programming Languages LISP

COP4020 Programming Assignment 1 - Spring 2011

LECTURE 16. Functional Programming

Functional Programming. Pure Functional Languages

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


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

SCHEME AND CALCULATOR 5b

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

CSc 520 Principles of Programming Languages

CS 314 Principles of Programming Languages

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

FP Foundations, Scheme

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT

6.184 Lecture 4. Interpretation. Tweaked by Ben Vandiver Compiled by Mike Phillips Original material by Eric Grimson

Documentation for LISP in BASIC

Programming Languages

An Introduction to Scheme

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

CSE 341 Section Handout #6 Cheat Sheet

CS61A Midterm 2 Review (v1.1)

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax

Intro. Scheme Basics. scm> 5 5. scm>

Functional Programming. Pure Functional Programming

6.037 Lecture 4. Interpretation. What is an interpreter? Why do we need an interpreter? Stages of an interpreter. Role of each part of the interpreter

The Typed Racket Guide

Principles of Programming Languages 2017W, Functional Programming

Typed Racket: Racket with Static Types

Introduction to Scheme

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

Scheme as implemented by Racket

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

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

CS450 - Structure of Higher Level Languages

CS 314 Principles of Programming Languages

Lisp. Versions of LISP

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

Scheme Quick Reference

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

YOUR NAME PLEASE: *** SOLUTIONS ***

Functional Programming

Turtles All The Way Down

Scheme Basics > (butfirst '(help!)) ()

Typed Scheme: Scheme with Static Types

Scheme Quick Reference

Functional Languages. Hwansoo Han

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

Sample Final Exam Questions

CSSE 304 Assignment #13 (interpreter milestone #1) Updated for Fall, 2018

Functional Programming. Big Picture. Design of Programming Languages

Why do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson

Fall Semester, The Metacircular Evaluator. Today we shift perspective from that of a user of computer langugaes to that of a designer of

CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang

An Explicit Continuation Evaluator for Scheme

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

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

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing

Introduction to Syntax Analysis Recursive-Descent Parsing

SOFTWARE ARCHITECTURE 6. LISP

Lists in Lisp and Scheme

Write a procedure powerset which takes as its only argument a set S and returns the powerset of S.

Functional Programming Languages (FPL)

Functional Programming - 2. Higher Order Functions

Thoughts on Assignment 4 Haskell: Flow of Control

Building a system for symbolic differentiation

Common LISP-Introduction

Programming Systems in Artificial Intelligence Functional Programming

How to Design Programs Languages

6.001: Structure and Interpretation of Computer Programs

(Func&onal (Programming (in (Scheme)))) Jianguo Lu

Introductory Scheme. Revision 1

Discussion 12 The MCE (solutions)

Building a system for symbolic differentiation

Modern Programming Languages. Lecture LISP Programming Language An Introduction

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

Essentials of Programming Languages Language

CS61A Notes Disc 11: Streams Streaming Along

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal)

INTRODUCTION TO SCHEME

Writing a Lexer. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, February 6, Glenn G.

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

Comp 311: Sample Midterm Examination

6.001 Notes: Section 8.1

Transcription:

Scheme: Strings Scheme: I/O CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Wednesday, April 5, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu 2017 Glenn G. Chappell

Review Scheme: Data quote, eval, & More Code quote suppresses the normal parameter evaluation. The leading single quote is shorthand for quote. > (quote (1 2 3)) ; Same as '(1 2 3) (1 2 3) eval evaluates its parameter. list returns a list of its arguments. > (list "hello" '+ 1 2 3)) ("hello" + 1 2 3) > (eval (cdr (list "hello" '+ 1 2 3))) 6 Return an empty list with '() or null. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 2

Review Scheme: Data Data Format [1/5] The dot notation originally used in S-expressions is also valid in Scheme. > '(1. 2) (1. 2) A list is really shorthand for the equivalent dot notation, again, just as in the original S-expression syntax. > '(1. (2. (3. (4. ())))) (1 2 3 4) Dot (.) is not a function. It is simply another way of typing S- expressions. If you want a normal function that puts things together the way dot does, use cons. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 3

Review Scheme: Data Data Format [2/5] The main building block for constructing data structures in Scheme is the pair. This is a node with two pointers. (1. 2) 1 2 We get the item referenced by the left pointer using car; similarly use cdr for the right pointer. > (car '(1. 2)) 1 > (cdr '(1. 2)) 2 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 4

Review Scheme: Data Data Format [3/5] Lists are constructed from pairs and null. (1 2 3) = (1. (2. (3. ()))) 1 2 3 NULL 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 5

Review Scheme: Data Data Format [4/5] The full story on the dot syntax is that the dot may optionally be added just before the last item of a list. (1 2 3) = (1. (2. (3. ()))) (1 2. 3) = (1. (2. 3)) 1 2 1 2 3 3 NULL 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 6

Review Scheme: Data Data Format [5/5] We can create arbitrary binary trees with the restriction that only leaves have data. ((((). 8). 1). (5. 1)) 1 5 1 NULL 8 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 7

Review Scheme: Data Taking a Varying Number of Parameters We wrote a procedure sum that, like +, takes an arbitrary number of parameters. A procedure call is a pair: (PROC. ARGS). And define will also take this form of a picture of a function call. (define (sum. args) )... How to make a recursive call on (cdr args)? (sum. (cdr args)) ; WRONG! (eval (cons sum (cdr args))) ; Okay (apply sum (cdr args)) (sum. (cdr args)) is just another way to write (sum cdr args), which is not what we want. ; Okay (and also clearer) 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 8

Review Scheme: Data Manipulating Trees Recall that a Scheme value is null, or a pair, or an atom. Any value for which both null? and pair? return #f is an atom. We can write procedures that deal with a structure, not as a list, but as a tree, traversing the tree and dealing with atoms in some way. A useful procedure is error, which, much like Haskell s error, takes a string, and crashes with a message if it executes. See data.scm. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 9

Scheme: Strings Basics [1/2] String literals in Scheme are surrounded by double quotes. "This is a string." The usual backslash escapes are accepted. "A newline: \na double quote: \" A backslash: \\" Check whether a value is a string with string?. > (string? "42") #t > (string? 42) #f 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 10

Scheme: Strings Basics [2/2] Get the length of a string with string-length. > (string-length "Hello!") 6 Concatenate strings with string-append. > (string-append "abc" "def" "ghi" "jklmnop") "abcdefghijklmnop" Get a substring with (substring STRING START PAST_END). > (substring "Howdy thar!" 2 7) ; Zero-based indices "wdy t" Includes the characters at indices 2, 3, 4, 5, 6, but not 7. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 11

Scheme: Strings Numeric Conversions Convert a number to a string using number->string. > (number->string 42) "42" Convert a string to a number using string->number. This returns the number, or #f if the conversion could not be done. So the result can be used in an if. > (string->number "42") 42 > (string->number "Hello!") #f (if COND THEN-EXPR ELSE-EXPR) Recall: When the above is evaluated, THEN-EXPR is chosen if COND evaluates to anything other than #f. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 12

Scheme: Strings Characters [1/2] Character literals generally have the form #\CHAR. #\A ; The 'A' character Some characters have special forms. #\newline #\space Check whether a value is a character with char?. > (char? #\x) #t > (char? "x") #f 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 13

Scheme: Strings Characters [2/2] Convert a character to its numeric version (ASCII value/unicode codepoint) with char->integer. Reverse: integer->char. > (char->integer #\A) 65 > (integer->char 65) #\A Convert between strings and lists of characters with string->list and list->string. > (string->list "Howdy thar!") (#\H #\o #\w #\d #\y #\space #\t #\h #\a #\r #\!) > (list->string '(#\a #\b #\c)) "abc" 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 14

Scheme: Strings Comparisons [1/3] We have seen the Scheme numeric comparison operators: = < <= > >=. These can be used only with numbers. Many Scheme types have their own equality functions, along with the other comparisons, if appropriate. > (string=? "abc" "def") #f > (string=? "42" 42) ERROR > (string<? "abc" "def") #t Also: string<=? string>? string>=? char=? char<? char<=? char>? char>=? 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 15

Scheme: Strings Comparisons [2/3] There are many kinds of equality in Scheme: same object in memory, same primitive value, etc. It is easy to get lost among the various equality functions (eq?, eqv?, etc.). Fortunately, Scheme has equal?. This can be called on any two values. It returns #f if they are of different types. Otherwise, it does an appropriate type-specific equality check. For numbers, it calls =. For strings, it calls string=?. For characters, it calls char=?. For two nulls (empty lists), it returns #t. For pairs, it recursively calls equal? on the cars and the cdrs. So it is a reasonable equality check for lists. > (equal? '(1 (2 3) ((4))) '(1 (2 3) ((4)))) #t 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 16

Scheme: Strings Comparisons [3/3] Because equal? always returns #f for parameters of different types, it may not do what you expect when given numbers. > (= 0 0.0) #t > (equal? 0 0.0) #t Thus, I offer the following rule of thumb. Use = for numeric equality. Use equal? for most other kinds of equality. If you want the code to indicate what type you are comparing, and flag type errors for other types, then use a type-specific equality function (e.g., string=?, char=?). Use other equality functions only if you know what you are doing. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 17

Scheme: I/O Console Output [1/2] Print a any value with display. String conversion is automatic. No trailing newline is printed. Print a newline with newline. Both of these return void, which does not print in the REPL. > (display "Howdy thar!") Howdy thar! > (newline) > (display #\A) A > (display '(42 #t (300))) (42 #t (300)) > (display +) #<procedure:+> 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 18

Scheme: I/O Console Output [2/2] To do multiple I/O calls in a single expression, use begin. This takes any number of parameters, evaluates them all, in order, and returns the value of the last one. > (begin (display "dog") (display "food") (display "love") ) dogfoodlove 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 19

Scheme: I/O Console Input [1/2] Read a line from the console with read-line. This takes no parameters. It returns the typed-in line with no trailing newline. How can we set a variable equal to the return value of read-line in a procedure? We want a local binding, not a global one. One way is to define inside the procedure. Another is to use let. (let ; Locally bind vars to values in the expression ) ( ) (VARIABLE1 VALUE1) (VARIABLEn VALUEn) ( EXPRESSION ) Scheme s let is much like Haskell s where, except that the definitions come before, instead of after. Punchline: Haskell has let also, but I prefer where. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 20

Scheme: I/O Console Input [2/2] TO DO Write a procedure to prompt for input, read a line, and then print it, with some explanation ( Here is what you typed: ). Done. See io.scm. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 21

Scheme: I/O Files Overview Scheme file I/O can be done with the usual open close sequence. On success, opening a file gives a value called a port, by which the open file can be accessed. This is passed to all other file-i/o functions, as usual. But Scheme includes wrappers around this functionality that are more convenient: call-with-output-file and call-with-input-file. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 22

Scheme: I/O Files Output [1/2] Procedure call-with-output-file takes two parameters: The filename (string). A 1-parameter procedure that takes an output port. Notes On failure, call-with-output-file raises an exception, which will crash if no error handling is done. On success it calls the given procedure, passing the port. The given procedure is responsible for closing the file, by passing the port to close-output-port. A variation, call-with-output-file*, closes the file automatically when the given procedure terminates. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 23

Scheme: I/O Files Output [2/2] Do file output by passing the port as a second argument to display or newline. Example use of call-with-output-file*: (define (do-output outport) (begin (display "Here is some file content." outport) (newline outport) ) ) (call-with-output-file* "myfile.txt" do-output) 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 24

Scheme: I/O Files Lambdas [1/2] We can do it all with a single procedure using a lambda. As in Haskell, this refers to an unnamed function (procedure). This: (define (f a b) (* a b)) is the same as this: (define f (lambda (a b) (* a b))) Scheme has first-class functions, so we can use a lambda without giving it a name. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 25

Scheme: I/O Files Lambdas [2/2] Here is our file output as a single expression. (call-with-output-file* "myfile.txt" (lambda (outport) (begin (display "Here is some file content." outport) (newline outport) ) ) ) 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 26

Scheme: I/O Files Input [1/3] Similarly, we can use call-with-input-file to do file input. This takes a filename and a procedure that takes an input port. The given procedure is responsible for closing the file, by passing the port to close-input-port. Or we can use call-with-inputfile*, which closes automatically. Read a line from a file by passing the port to read-line. As before, this normally returns the line as a string with no trailing newline. However, on end of file, read-line returns an EOF object. Check for this by passing the return value to the predicate eof-object?. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 27

Scheme: I/O Files Input [2/3] Suppose we are reading a file, line by line. How do we repeat? The let procedure has a useful extension: we can give it a name: (let NAME ( ) ) (VARIABLE1 VALUE1) (VARIABLEn VALUEn) ( EXPRESSION ) Within EXPRESSION, we can use NAME as a procedure taking n arguments. These become the values of VARIABLE1 through VARIABLEn in that invocation of the procedure. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 28

Scheme: I/O Files Input [3/3] TO DO Write a procedure that reads a file, line by line, and prints each line. Extra credit: add line numbers. Done. See io.scm. 5 Apr 2017 CS F331 / CSCE A331 Spring 2017 29