Scheme as implemented by Racket

Size: px
Start display at page:

Download "Scheme as implemented by Racket"

Transcription

1 Scheme as implemented by Racket (Simple view:) Racket is a version of Scheme. (Full view:) Racket is a platform for implementing and using many languages, and Scheme is one of those that come out of the box. Racket s version of Scheme is somewhat different from the standards, e.g., function names, some features. My slides are right for Racket, but may fail with standard Scheme. But same principles. My slides give you a taste, but there are a lot of useful things I won t cover. 1 / 33

2 Basic Data Types And Syntax of Their Literals Booleans: #t, #f Numbers: 42 (integers), 1/3 (rational numbers), 42.5 (floating-point numbers), 3+4i (complex numbers) Strings: "hello" Single characters: #\h stands for the letter h. Symbols: User-defined atomic values. You think up a name, put a single-quote in front. Four examples: Firefox Chrome Edge Safari Great for tags, labels, enumerations. Symbols are not strings. You can t append, split, ask for the nth character... 2 / 33

3 Expressions Literals: Examples on the previous slide. Identifiers: E.g., +, my-angle/time Procedure/Function Applications: (proc param1 param2...) proc and parameters are expressions. proc should evaluate to a procedure. E.g., (sin (/ 0.2 2)) E.g., ((if #t sin cos) (/ 0.2 2)) Special Forms: (keyword expr expr...) For definitions, conditionals, other features... They have their own slides. 3 / 33

4 Some Boolean Operations (not expr) (and expr expr...) Short-circuits. (and) gives #t. (or expr expr...) Short-circuits. (or) gives #f. (boolean? expr) Tests whether you have a boolean value. 4 / 33

5 Some Number Operations + - * / max min can take multiple operands. quotient remainder abs sqrt sin cos tan etc. (expt b x) means b x. (exp x) means e x. (log x) means ln x. = < <= > >= can take multiple operands, e.g., (> x y z) means x > y > z. number? tests whether a value is a number. complex?, real?, rational?, integer? test what kind of number. number->string string->number (has ways to indicate parse errors) 5 / 33

6 Some String Operations (string-length str): length. (string-ref str k): character at position k (start from 0). (substring str i j) like Python s str[i:j]. (substring str i) like str[i:]. (string-append str1 str2...): concatenation. (string-append) gives the empty string. string=? string<? string<=? string>? string>=? Comparisons. Can take multiple operands. There are also case-insensitive versions. string? tests whether a value is a string. 6 / 33

7 Equality Equality is a mess. Three kinds, each with its intention and but s. eq? Good for booleans and symbols. Pointer equality for most aggregates, e.g., strings, lists. Complicated rules for numbers. Intention: Fast, just compare two machine words. eqv? Good for characters. Complicated rules for numbers, and different from eq?. (Rationale: Choices in treating floating-point s NaN and signed zero.) Most other types: Same as eq?. equal? Structural equality for most aggregates, i.e., comparing contents. 7 / 33

8 Definitions Give cool names to cool things. Examples: ; A constant. ( define my- width/ height (/ 4 3)) ; A function with 1 parameter. ( define ( greet person) ( string - append " hello " person)) ; A function with 2 parameters. ( define (my- log base x) (/ (log x) (log base))) Recursion is allowed. 8 / 33

9 Anonymous Functions/Procedures (lambda, λ) (Terminology: procedure expected to be effectful, e.g., I/O; function expected to be effect-free. Not strictly enforced though.) Can write a function without name; procedure expression. (lambda (param1 param2...) body) Example: (lambda (base x) (/ (log x) (log base))) Example usage: ( (lambda (base x) (/ (log x) (log base))) 128 2) Function definition (define (f x y) body) is short-hand for (define f (lambda (x y) body)). May also write λ. 9 / 33

10 Conditionals If-then-else: (if test then-expr else-expr) Actually test can be non-boolean treated as true. Multiple conditions: (cond [(> x y) (sin x)] [(< x y) (cos y)] [else 0]) If x > y then sin x; else if x < y then cos y; else 0. Test results can be non-boolean treated as true. Furthermore you can obtain and use it: (cond [(+ 4 2) => (lambda (x) (* x x))] [else 0]) This gives / 33

11 and, or As Conditionals (and expr expr...) Evaluates from left to right, stops as soon as #f happens. Otherwise, the last expr is the answer. Examples: (and 42 #f "hello") gives #f (and 42 hey "hello") gives "hello" (and) gives #t (or expr expr...) Evaluates from left to right, stops as soon as non-#f happens, and that s the answer. Otherwise, the answer is #f. Examples: (or 42 hey "hello") gives 42 (or (and #f) #f) gives #f (or) gives #f 11 / 33

12 Local Bindings Non-Recursive Local definitions for use in just one expression. (let ([x expr1] [y expr2]) (+ x y (* 2 x y))) Compute x + y + 2xy, where x = expr1 and y = expr2. expr1 and expr2 cannot see the local x or y; they see outer names. (let ([x 3]) (let ([x (* x x)]) ; (* 3 3) x)) gives 9 and is not a recursion. let* allows later bindings to see earlier bindings. (let* ([x 5] [y (+ x 1)]) ; (+ 5 1) (+ x y (* 2 x y))) 12 / 33

13 Local Bindings Recursive letrec allows recursive bindings (self or mutually). (letrec ([fac (lambda (n) (if (= n 0) 1 (* n (fac (- n 1)))))] [even (lambda (n) (or (= n 0) (not (odd (- n 1)))))] [odd (lambda (n) (not (even (- n 1))))]) (even (fac 5))) 13 / 33

14 Recommended Code Layout Jokes: Pythonic Scheme inspired by Pythonic Java. Serious: Open parentheses then immediately first word. Procedure definition: Body starts on new line, indented. Long expression: Parts start on new lines, indented. Closing parentheses not on new lines. Most editors have Scheme modes that can do these for you. 14 / 33

15 Compound Data: Pairs And Lists Cons cell, 2-tuple, pair. Syntax: (cons x y). Can imagine a pair of pointers. Short-hand if both fields are literals: (5. "hello"). What if the 2nd field is (points to) a cons cell again, and its 2nd field is a cons cell again,...? Singly-linked list. Special support for lists: Empty list: () (list x y z) = (cons x (cons y (cons z ()))) List literal: (42 "hi" Chrome) The Chrome means the symbol Chrome. 15 / 33

16 Some Pair And List Operations Tests: pair?, list?, null? First field of a pair: car Second field of a pair: cdr First item of a list: first, same answer as car, but only for lists. Tail of a list: rest, same answer as cdr, but only for lists. length (list-ref lst i): item at position i. (append lst1 lst2...): concatenation. reverse Higher-order functions: map, filter, foldr, foldl... discussed later. 16 / 33

17 Compound Data: User-Defined Records (struct dim (width height)) creates a new record type of two fields, with these support utilities: (dim 4 7) constructs a value of this type. dim? tests for this type. dim-width, dim-height: field accessors. struct-copy: Clones a record while replacing some field values. Original record unchanged functional update. (define d1 (dim 4 7)) ( define d2 ( struct - copy dim d1 [ width 5])) Then d2 is (dim 5 7). 17 / 33

18 Pattern Matching Test for literal, cons cell, or record type, and get the content too. ( struct dim ( width height)) (define (foo x) (match x [ () nada] [(cons b _) b] [(dim w h) (* w h)])) (foo ()) gives nada (foo (1 2 3)) gives 1 (foo (dim 4 7)) gives / 33

19 Input And Output: stdin, stdout, stderr stdout and stdin: (display 5), (display "hello") (newline), (displayln 5), (displayln "hello") (printf "~a = ~a~n" "price" 5) Aside: (format "~a = ~a~n" "price" 5) gives the string rather than outputs it. (read-line) (read-string 10) reads up to the upper bound. If EOF, returns eof, can use eq? or eof-object? to test. stderr: eprintf is like printf but goes to stderr. 19 / 33

20 Input And Output: Ports Racket has ports, analogous to Java Reader/Writer behind it can be file, string, network connection, message queue, user-defined. (call -with -output -file* "out.txt" #: mode text #: exists replace (lambda (op) ( displayln 6 op) (fprintf op "~a~n" 7))) (let ([s (call -with -input -file* "in.txt" #:mode text (lambda (ip) (read -string 10 ip)))]) (displayln s)) 20 / 33

21 Sequencing You may want to evaluate multiple expressions (in the order you specify) because the point is their effects. (begin ( displayln " Please enter your name") (read -line)) It returns what the last expression returns. (begin0 expr1 expr2...) returns what expr1 returns. (The other expressions are still evaluated.) (when (> x 0) expr1 expr2...) If true, evaluates the expressions, returns what the last one returns. If false, returns #<void>. 21 / 33

22 Sequencing Some constructs already support multiple expressions and sequencing, you don t need to wrap with begin: Conditionals and pattern matching: (cond [test expr1 expr2...] [...]...) (match expr [pattern expr1 expr2...] [...]...) Procedure bodies: (define (f x) expr1 expr2...) (lambda (x) expr1 expr2...) Bodies of let etc.: (let ([x 5] [y 42]) expr1 expr2...) Also, and, or already do sequencing. 22 / 33

23 Mutable Variables (define v 5) (define (f x) (+ v x)) (f 0) ; gives 5 (set! v 6) (f 0) ; gives 6 Mutable pairs, lists, strings, arrays... are also available. Use mutation judiciously. It is much less necessary than most people think. 23 / 33

24 map (map f (list x y z)) equals (list (f x) (f y) (f z)) Can you write your own version? ( define (my- map f lst) (match lst [ () ()] [(cons hd tl) (cons (f hd) (my-map f tl))])) Remark: Racket s map is more general can take several lists, e.g., (map + (1 2 3) ( )) equals ( ). 24 / 33

25 filter (filter number? (9 "4" 0 "1" "6" 5)) equals (9 0 5). Can you write your own version? ( define (my- filter pred lst) (match lst [ () ()] [(cons hd tl) (if (pred hd) ( cons hd (my- filter pred tl)) (my-filter pred tl))])) 25 / 33

26 foldr Motivation Sum up a list, write your own recursion, first way: ( define (my- sum lst) (match lst [ () 0] [(cons hd tl) (+ hd (my-sum tl))])) Multiply a list, write your own recursion, first way: ( define (my- product lst) (match lst [ () 1] [(cons hd tl) (* hd (my-product tl))])) What is different? What stays the same? Can you factor it out? ( define ( foldr binop z lst) (match lst [ () z] [(cons hd tl) (binop hd (foldr binop z tl))])) 26 / 33

27 foldr If your function satisfies: (g ()) equals z (g (cons hd tl)) equals (binop hd (g tl)) Then (g lst) equals (foldr binop z lst) Intuitively, they look like a (b (c z)), writing for binop, if the list is (list a b c). Not always obvious. Some refactoring can help. Telltale sign: The recursion is simply on the list tail. Example: Next slide shows why my-map is a foldr. Example: my-filter is also a foldr. 27 / 33

28 my-map is a foldr = = = (define (my-map f lst) (match lst [ () ()] [(cons hd tl) (cons (f hd) (my-map f tl))])) (define (my-map f lst) (define (g lst) (match lst [ () ()] [(cons hd tl) (cons (f hd) (g tl))])) (g lst)) (define (my-map f lst) (define (binop x r) (cons (f x) r)) (define (g lst) (match lst [ () ()] [(cons hd tl) (binop hd (g tl))])) (g lst)) (define (my-map f lst) (define (binop x r) (cons (f x) r)) (foldr binop () lst)) 28 / 33

29 foldl Motivation Sum up a list, write your own recursion, second way (accumulator): ( define (my- sum lst) ; ( loop accum lst) computes accum + sum of lst ( define ( loop accum lst) (match lst [ () accum] [(cons hd tl) (loop (+ accum hd) tl)])) (loop 0 lst)) Multiply a list, write your own recursion, first way: ( define (my- product lst) ; ( loop accum lst) computes accum * product of lst ( define ( loop accum lst) (match lst [ () accum] [(cons hd tl) (loop (* accum hd) tl)])) (loop 1 lst)) What is different? What stays the same? Can you factor it out? 29 / 33

30 foldl ( define ( foldl binop a lst) (match lst [ () a] [(cons hd tl) (foldl binop (binop a hd) tl)])) Intuitively, (foldl binop a (list x y z)) looks like ((a x) y) z, writing for binop. 30 / 33

31 Procedure-Call Stack (define (f n) (... (f (- n 1))...) (displayln (+ (f 4) (f 1) (f 6))) Control-flow jumps into f; later automagically knows where to return to. Sufficiently elegant solutions are indistiguishable from magic. A stack is used to remember where to return to. Call stack. Benefit: Supports recursion (self and mutual). Price: Each invocation holds up Θ(1) space until it finishes. (Invented by Peter Naur for Algol. Before him, each procedure was given fixed space for return address. Recursion disallowed. People didn t believe Naur when he got this to work.) You will understand this intimately in Part II of the course. 31 / 33

32 Non-Tail Calls and Tail Calls Non-tail call: There is post-processing after the call returns. ( define (my- sum lst) (match lst [ () 0] [(cons hd tl) (+ hd (my-sum tl))])) Takes Θ(n) space (if n is the list length). Tail call: No post-processing after the call returns. No need to remember return address, just jump. ( define (my- sum lst) ( define ( loop accum lst) (match lst [ () accum] [(cons hd tl) (loop (+ accum hd) tl)])) (loop 0 lst)) Literally a loop. Takes O(1) space. 32 / 33

33 Nested Lambdas A procedure that returns a procedure. (define map1 (lambda (f) (lambda (lst) (map f lst)))) Sample usage: ((map1 abs) (-1-4)) Real usage: (map (map1 abs) ((-1-4) (-2-5))) Note: (map (map abs)...) doesn t work wrong number of parameters. 33 / 33

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Winter 2003 February 10, 2003 1 Introduction This document is a quick reference guide to common features of the Scheme language. It is by no means intended to be a complete

More information

Scheme Quick Reference

Scheme Quick Reference Scheme Quick Reference COSC 18 Fall 2003 This document is a quick reference guide to common features of the Scheme language. It is not intended to be a complete language reference, but it gives terse summaries

More information

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

SCHEME 7. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. October 29, 2015 SCHEME 7 COMPUTER SCIENCE 61A October 29, 2015 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

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

Summer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define CS 6A Scheme Summer 207 Discussion 0: July 25, 207 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen COP4020 Programming Languages Functional Programming Prof. Robert van Engelen Overview What is functional programming? Historical origins of functional programming Functional programming today Concepts

More information

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

SCHEME 8. 1 Introduction. 2 Primitives COMPUTER SCIENCE 61A. March 23, 2017 SCHEME 8 COMPUTER SCIENCE 61A March 2, 2017 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

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

Fall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 208 Discussion 8: October 24, 208 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

Administrivia. Simple data types

Administrivia. Simple data types Administrivia Lists, higher order procedures, and symbols 6.037 - Structure and Interpretation of Computer Programs Mike Phillips (mpp) Massachusetts Institute of Technology Project 0 was due today Reminder:

More information

Essentials of Programming Languages Language

Essentials of Programming Languages Language Essentials of Programming Languages Language Version 5.3 August 6, 2012 The Essentials of Programming Languages language in DrRacket provides a subset of functions and syntactic forms of racket mostly

More information

Essentials of Programming Languages Language

Essentials of Programming Languages Language Essentials of Programming Languages Language Version 6.90.0.26 April 20, 2018 The Essentials of Programming Languages language in DrRacket provides a subset of functions and syntactic forms of racket mostly

More information

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

Fall 2017 Discussion 7: October 25, 2017 Solutions. 1 Introduction. 2 Primitives CS 6A Scheme Fall 207 Discussion 7: October 25, 207 Solutions Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write

More information

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

Scheme. Functional Programming. Lambda Calculus. CSC 4101: Programming Languages 1. Textbook, Sections , 13.7 Scheme Textbook, Sections 13.1 13.3, 13.7 1 Functional Programming Based on mathematical functions Take argument, return value Only function call, no assignment Functions are first-class values E.g., functions

More information

CSC 533: Programming Languages. Spring 2015

CSC 533: Programming Languages. Spring 2015 CSC 533: Programming Languages Spring 2015 Functional programming LISP & Scheme S-expressions: atoms, lists functional expressions, evaluation, define primitive functions: arithmetic, predicate, symbolic,

More information

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

Spring 2018 Discussion 7: March 21, Introduction. 2 Primitives CS 61A Scheme Spring 2018 Discussion 7: March 21, 2018 1 Introduction In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme

More information

LECTURE 16. Functional Programming

LECTURE 16. Functional Programming LECTURE 16 Functional Programming WHAT IS FUNCTIONAL PROGRAMMING? Functional programming defines the outputs of a program as a mathematical function of the inputs. Functional programming is a declarative

More information

CSE 341 Lecture 16. More Scheme: lists; helpers; let/let*; higher-order functions; lambdas

CSE 341 Lecture 16. More Scheme: lists; helpers; let/let*; higher-order functions; lambdas CSE 341 Lecture 16 More Scheme: lists; helpers; let/let*; higher-order functions; lambdas slides created by Marty Stepp http://www.cs.washington.edu/341/ Lists (list expr2... exprn) '(value1 value2...

More information

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

SCHEME The Scheme Interpreter. 2 Primitives COMPUTER SCIENCE 61A. October 29th, 2012 SCHEME COMPUTER SCIENCE 6A October 29th, 202 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs, we will eventually

More information

SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

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

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Organization of Programming Languages CS3200/5200N. Lecture 11

Organization of Programming Languages CS3200/5200N. Lecture 11 Organization of Programming Languages CS3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Functional vs. Imperative The design of the imperative languages

More information

Functional Programming. Pure Functional Programming

Functional Programming. Pure Functional Programming Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

More information

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

More information

CSE 341 Section Handout #6 Cheat Sheet

CSE 341 Section Handout #6 Cheat Sheet Cheat Sheet Types numbers: integers (3, 802), reals (3.4), rationals (3/4), complex (2+3.4i) symbols: x, y, hello, r2d2 booleans: #t, #f strings: "hello", "how are you?" lists: (list 3 4 5) (list 98.5

More information

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages. Lecture LISP Programming Language An Introduction Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

More information

CS450 - Structure of Higher Level Languages

CS450 - Structure of Higher Level Languages Spring 2018 Streams February 24, 2018 Introduction Streams are abstract sequences. They are potentially infinite we will see that their most interesting and powerful uses come in handling infinite sequences.

More information

COP4020 Programming Assignment 1 - Spring 2011

COP4020 Programming Assignment 1 - Spring 2011 COP4020 Programming Assignment 1 - Spring 2011 In this programming assignment we design and implement a small imperative programming language Micro-PL. To execute Mirco-PL code we translate the code to

More information

How to Design Programs Languages

How to Design Programs Languages How to Design Programs Languages Version 4.1 August 12, 2008 The languages documented in this manual are provided by DrScheme to be used with the How to Design Programs book. 1 Contents 1 Beginning Student

More information

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

Scheme Tutorial. Introduction. The Structure of Scheme Programs. Syntax Scheme Tutorial Introduction Scheme is an imperative language with a functional core. The functional core is based on the lambda calculus. In this chapter only the functional core and some simple I/O is

More information

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

6.034 Artificial Intelligence February 9, 2007 Recitation # 1. (b) Draw the tree structure corresponding to the following list. 6.034 Artificial Intelligence February 9, 2007 Recitation # 1 1 Lists and Trees (a) You are given two lists: (define x (list 1 2 3)) (define y (list 4 5 6)) What would the following evaluate to: (append

More information

Streams and Evalutation Strategies

Streams and Evalutation Strategies Data and Program Structure Streams and Evalutation Strategies Lecture V Ahmed Rezine Linköpings Universitet TDDA69, VT 2014 Lecture 2: Class descriptions - message passing ( define ( make-account balance

More information

CSCC24 Functional Programming Scheme Part 2

CSCC24 Functional Programming Scheme Part 2 CSCC24 Functional Programming Scheme Part 2 Carolyn MacLeod 1 winter 2012 1 Based on slides from Anya Tafliovich, and with many thanks to Gerald Penn and Prabhakar Ragde. 1 The Spirit of Lisp-like Languages

More information

Functional Programming - 2. Higher Order Functions

Functional Programming - 2. Higher Order Functions Functional Programming - 2 Higher Order Functions Map on a list Apply Reductions: foldr, foldl Lexical scoping with let s Functional-11, CS5314, Sp16 BGRyder 1 Higher Order Functions Functions as 1st class

More information

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

11/6/17. Functional programming. FP Foundations, Scheme (2) LISP Data Types. LISP Data Types. LISP Data Types. Scheme. LISP: John McCarthy 1958 MIT Functional programming FP Foundations, Scheme (2 In Text: Chapter 15 LISP: John McCarthy 1958 MIT List Processing => Symbolic Manipulation First functional programming language Every version after the

More information

Scheme: Strings Scheme: I/O

Scheme: Strings Scheme: I/O 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

More information

An Introduction to Scheme

An Introduction to Scheme An Introduction to Scheme Stéphane Ducasse stephane.ducasse@inria.fr http://stephane.ducasse.free.fr/ Stéphane Ducasse 1 Scheme Minimal Statically scoped Functional Imperative Stack manipulation Specification

More information

Box-and-arrow Diagrams

Box-and-arrow Diagrams Box-and-arrow Diagrams 1. Draw box-and-arrow diagrams for each of the following statements. What needs to be copied, and what can be referenced with a pointer? (define a ((squid octopus) jelly sandwich))

More information

YOUR NAME PLEASE: *** SOLUTIONS ***

YOUR NAME PLEASE: *** SOLUTIONS *** YOUR NAME PLEASE: *** SOLUTIONS *** Computer Science 201b SAMPLE Exam 1 SOLUTIONS February 15, 2015 Closed book and closed notes. No electronic devices. Show ALL work you want graded on the test itself.

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

University of Massachusetts Lowell

University of Massachusetts Lowell University of Massachusetts Lowell 91.301: Organization of Programming Languages Fall 2002 Quiz 1 Solutions to Sample Problems 2 91.301 Problem 1 What will Scheme print in response to the following statements?

More information

Lecture #24: Programming Languages and Programs

Lecture #24: Programming Languages and Programs Lecture #24: Programming Languages and Programs A programming language is a notation for describing computations or processes. These range from low-level notations, such as machine language or simple hardware

More information

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

Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions. 1 Calculator. calc> (+ 2 2) 4 CS 61A Interpreters and Tail Calls Fall 2017 Discussion 8: November 1, 2017 Solutions 1 Calculator We are beginning to dive into the realm of interpreting computer programs that is, writing programs that

More information

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

Streams, Delayed Evaluation and a Normal Order Interpreter. CS 550 Programming Languages Jeremy Johnson Streams, Delayed Evaluation and a Normal Order Interpreter CS 550 Programming Languages Jeremy Johnson 1 Theme This lecture discusses the stream model of computation and an efficient method of implementation

More information

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

;;; Determines if e is a primitive by looking it up in the primitive environment. ;;; Define indentation and output routines for the output for Page 1/11 (require (lib "trace")) Allow tracing to be turned on and off (define tracing #f) Define a string to hold the error messages created during syntax checking (define error msg ""); Used for fancy

More information

Introduction to Scheme

Introduction to Scheme How do you describe them Introduction to Scheme Gul Agha CS 421 Fall 2006 A language is described by specifying its syntax and semantics Syntax: The rules for writing programs. We will use Context Free

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 16: Functional Programming Zheng (Eddy Zhang Rutgers University April 2, 2018 Review: Computation Paradigms Functional: Composition of operations on data.

More information

A Brief Introduction to Scheme (II)

A Brief Introduction to Scheme (II) A Brief Introduction to Scheme (II) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Lists Scheme II p.1/29 Lists Aggregate data

More information

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

CS61A Summer 2010 George Wang, Jonathan Kotker, Seshadri Mahalingam, Eric Tzeng, Steven Tang CS61A Notes Week 6B: Streams Streaming Along A stream is an element and a promise to evaluate the rest of the stream. You ve already seen multiple examples of this and its syntax in lecture and in the

More information

Discussion 4. Data Abstraction and Sequences

Discussion 4. Data Abstraction and Sequences Discussion 4 Data Abstraction and Sequences Data Abstraction: The idea of data abstraction is to conceal the representation of some data and to instead reveal a standard interface that is more aligned

More information

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda

Functional abstraction. What is abstraction? Eating apples. Readings: HtDP, sections Language level: Intermediate Student With Lambda Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

More information

Functional abstraction

Functional abstraction Functional abstraction Readings: HtDP, sections 19-24. Language level: Intermediate Student With Lambda different order used in lecture section 24 material introduced much earlier sections 22, 23 not covered

More information

CS115 - Module 9 - filter, map, and friends

CS115 - Module 9 - filter, map, and friends Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, Intermezzo 3 (Section 18); Sections 19-23. Abstraction abstraction, n. 3a.... The process of isolating properties or

More information

Documentation for LISP in BASIC

Documentation for LISP in BASIC Documentation for LISP in BASIC The software and the documentation are both Copyright 2008 Arthur Nunes-Harwitt LISP in BASIC is a LISP interpreter for a Scheme-like dialect of LISP, which happens to have

More information

Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Typed Racket: Racket with Static Types Version 5.0.2 Sam Tobin-Hochstadt November 6, 2010 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type

More information

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

Announcements. The current topic: Scheme. Review: BST functions. Review: Representing trees in Scheme. Reminder: Lab 2 is due on Monday at 10:30 am. The current topic: Scheme! Introduction! Object-oriented programming: Python Functional programming: Scheme! Introduction! Numeric operators, REPL, quotes, functions, conditionals! Function examples, helper

More information

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

Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs. Lexical addressing Computer Science 21b (Spring Term, 2015) Structure and Interpretation of Computer Programs Lexical addressing The difference between a interpreter and a compiler is really two points on a spectrum of possible

More information

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example.

Racket. CSE341: Programming Languages Lecture 14 Introduction to Racket. Getting started. Racket vs. Scheme. Example. Racket Next 2+ weeks will use the Racket language (not ML) and the DrRacket programming environment (not emacs) Installation / basic usage instructions on course website CSE34: Programming Languages Lecture

More information

Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt

Procedural abstraction SICP Data abstractions. The universe of procedures forsqrt. Procedural abstraction example: sqrt Data abstractions Abstractions and their variations Basic data abstractions Why data abstractions are useful Procedural abstraction Process of procedural abstraction Define formal parameters, capture process

More information

Freeing memory is a pain. Need to decide on a protocol (who frees what?) Pollutes interfaces Errors hard to track down

Freeing memory is a pain. Need to decide on a protocol (who frees what?) Pollutes interfaces Errors hard to track down Freeing memory is a pain Need to decide on a protocol (who frees what?) Pollutes interfaces Errors hard to track down 1 Freeing memory is a pain Need to decide on a protocol (who frees what?) Pollutes

More information

The Typed Racket Guide

The Typed Racket Guide The Typed Racket Guide Version 5.3.6 Sam Tobin-Hochstadt and Vincent St-Amour August 9, 2013 Typed Racket is a family of languages, each of which enforce

More information

A brief tour of history

A brief tour of history Introducing Racket λ A brief tour of history We wanted a language that allowed symbolic manipulation Scheme The key to understanding LISP is understanding S-Expressions Racket List of either atoms or

More information

Programming Languages: Application and Interpretation

Programming Languages: Application and Interpretation Programming Languages: Application and Interpretation Version 6.7 October 26, 2016 This is the documentation for the software accompanying the textbook Programming Languages: Application and Interpretation

More information

Project 2: Scheme Interpreter

Project 2: Scheme Interpreter Project 2: Scheme Interpreter CSC 4101, Fall 2017 Due: 12 November 2017 For this project, you will implement a simple Scheme interpreter in C++ or Java. Your interpreter should be able to handle the same

More information

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

CS 61A Interpreters, Tail Calls, Macros, Streams, Iterators. Spring 2019 Guerrilla Section 5: April 20, Interpreters. CS 61A Spring 2019 Guerrilla Section 5: April 20, 2019 1 Interpreters 1.1 Determine the number of calls to scheme eval and the number of calls to scheme apply for the following expressions. > (+ 1 2) 3

More information

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))

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)) SCHEME 0 COMPUTER SCIENCE 6A July 26, 206 0. Warm Up: Conditional Expressions. What does Scheme print? scm> (if (or #t (/ 0 (/ 0 scm> (if (> 4 3 (+ 2 3 4 (+ 3 4 (* 3 2 scm> ((if (< 4 3 + - 4 00 scm> (if

More information

More Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list?

More Scheme CS 331. Quiz. 4. What is the length of the list (()()()())? Which element does (car (cdr (x y z))) extract from the list? More Scheme CS 331 Quiz 1. What is (car ((2) 3 4))? (2) 2. What is (cdr ((2) (3) (4)))? ((3)(4)) 3. What is (cons 2 (2 3 4))? (2 2 3 4) 4. What is the length of the list (()()()())? 4 5. Which element

More information

INTRODUCTION TO SCHEME

INTRODUCTION TO SCHEME INTRODUCTION TO SCHEME PRINCIPLES OF PROGRAMMING LANGUAGES Norbert Zeh Winter 2019 Dalhousie University 1/110 SCHEME: A FUNCTIONAL PROGRAMMING LANGUAGE Functions are first-class values: Can be passed as

More information

Module 8: Local and functional abstraction

Module 8: Local and functional abstraction Module 8: Local and functional abstraction Readings: HtDP, Intermezzo 3 (Section 18); Sections 19-23. We will cover material on functional abstraction in a somewhat different order than the text. We will

More information

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Scheme in Scheme: The Metacircular Evaluator Eval and Apply Scheme in Scheme: The Metacircular Evaluator Eval and Apply CS21b: Structure and Interpretation of Computer Programs Brandeis University Spring Term, 2015 The metacircular evaluator is A rendition of Scheme,

More information

Functional Programming

Functional Programming Functional Programming CS331 Chapter 14 Functional Programming Original functional language is LISP LISt Processing The list is the fundamental data structure Developed by John McCarthy in the 60 s Used

More information

6.001 SICP. Types. Types compound data. Types simple data. Types. Types procedures

6.001 SICP. Types. Types compound data. Types simple data. Types. Types procedures Today s topics Types of objects and procedures Procedural abstractions Capturing patterns across procedures Higher Order Procedures Types (+ 5 1) ==> 15 (+ "hi 5) ;The object "hi", passed as the first

More information

Programming Languages. Function-Closure Idioms. Adapted from Dan Grossman's PL class, U. of Washington

Programming Languages. Function-Closure Idioms. Adapted from Dan Grossman's PL class, U. of Washington Programming Languages Function-Closure Idioms Adapted from Dan Grossman's PL class, U. of Washington More idioms We know the rule for lexical scope and function closures Now what is it good for A partial

More information

Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Copyright 2016 Elsevier 1 Chapter11_Functional_Languages_4e - Tue November 21, 2017 Historical Origins The imperative

More information

Introduction to Functional Programming

Introduction to Functional Programming Introduction to Functional Programming Xiao Jia xjia@cs.sjtu.edu.cn Summer 2013 Scheme Appeared in 1975 Designed by Guy L. Steele Gerald Jay Sussman Influenced by Lisp, ALGOL Influenced Common Lisp, Haskell,

More information

CONCEPTS OF PROGRAMMING LANGUAGES Solutions for Mid-Term Examination

CONCEPTS OF PROGRAMMING LANGUAGES Solutions for Mid-Term Examination COMPUTER SCIENCE 320 CONCEPTS OF PROGRAMMING LANGUAGES Solutions for Mid-Term Examination FRIDAY, MARCH 3, 2006 Problem 1. [25 pts.] A special form is an expression that is not evaluated according to the

More information

Functional Programming Languages (FPL)

Functional Programming Languages (FPL) Functional Programming Languages (FPL) 1. Definitions... 2 2. Applications... 2 3. Examples... 3 4. FPL Characteristics:... 3 5. Lambda calculus (LC)... 4 6. Functions in FPLs... 7 7. Modern functional

More information

CS 360 Programming Languages Interpreters

CS 360 Programming Languages Interpreters CS 360 Programming Languages Interpreters Implementing PLs Most of the course is learning fundamental concepts for using and understanding PLs. Syntax vs. semantics vs. idioms. Powerful constructs like

More information

Functional Programming and Haskell

Functional Programming and Haskell Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

More information

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

CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) CS61A Discussion Notes: Week 11: The Metacircular Evaluator By Greg Krimer, with slight modifications by Phoebus Chen (using notes from Todd Segal) What is the Metacircular Evaluator? It is the best part

More information

Programming Languages

Programming Languages Programming Languages Tevfik Koşar Lecture - XIII March 2 nd, 2006 1 Roadmap Functional Languages Lambda Calculus Intro to Scheme Basics Functions Bindings Equality Testing Searching 2 1 Functional Languages

More information

Functional programming with Common Lisp

Functional programming with Common Lisp Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions

More information

Functional Languages. Hwansoo Han

Functional Languages. Hwansoo Han Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm

More information

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia

CPL 2016, week 10. Clojure functional core. Oleg Batrashev. April 11, Institute of Computer Science, Tartu, Estonia CPL 2016, week 10 Clojure functional core Oleg Batrashev Institute of Computer Science, Tartu, Estonia April 11, 2016 Overview Today Clojure language core Next weeks Immutable data structures Clojure simple

More information

Functional Programming Languages (FPL)

Functional Programming Languages (FPL) Functional Programming Languages (FPL) 1. Definitions... 3 2. Applications... 3 3. Examples... 4 4. FPL Characteristics:... 5 5. Lambda calculus (LC)... 6 5.1. LC expressions forms... 6 5.2. Semantic of

More information

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages Functional Programming Pure functional PLs S-expressions cons, car, cdr Defining functions read-eval-print loop of Lisp interpreter Examples of recursive functions Shallow, deep Equality testing 1 Pure

More information

User-defined Functions. Conditional Expressions in Scheme

User-defined Functions. Conditional Expressions in Scheme User-defined Functions The list (lambda (args (body s to a function with (args as its argument list and (body as the function body. No quotes are needed for (args or (body. (lambda (x (+ x 1 s to the increment

More information

Principles of Programming Languages

Principles of Programming Languages Principles of Programming Languages www.cs.bgu.ac.il/~ppl172 Lesson 6 - Defining a Programming Language Bottom Up Collaboration and Management - Elements of Programming Dana Fisman 1 What we accomplished

More information

Common Lisp. Blake McBride

Common Lisp. Blake McBride Contents Common Lisp Blake McBride (blake@mcbride.name) 1 Data Types 2 2 Numeric Hierarchy 3 3 Comments 3 4 List Operations 4 5 Evaluation and Quotes 5 6 String Operations 5 7 Predicates 6 8 Math Predicates

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages CS 314 Principles of Programming Languages Lecture 17: Functional Programming Zheng (Eddy Zhang Rutgers University April 4, 2018 Class Information Homework 6 will be posted later today. All test cases

More information

Warm-up and Memoization

Warm-up and Memoization CSE341 Spring 05 Due Wednesday, May 11 Assignment 4 Part I Warm-up and Memoization Warm-up As a warm-up, write the following Scheme functions: 1. Write the function foldl of the form (foldl func initial

More information

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

Scheme: Data. CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, Glenn G. Scheme: Data CS F331 Programming Languages CSCE A331 Programming Language Concepts Lecture Slides Monday, April 3, 2017 Glenn G. Chappell Department of Computer Science University of Alaska Fairbanks ggchappell@alaska.edu

More information

Symbolic Computation and Common Lisp

Symbolic Computation and Common Lisp Symbolic Computation and Common Lisp Dr. Neil T. Dantam CSCI-56, Colorado School of Mines Fall 28 Dantam (Mines CSCI-56) Lisp Fall 28 / 92 Why? Symbolic Computing: Much of this course deals with processing

More information

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.

Lecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)

More information

Introduction to Functional Programming in Haskell 1 / 56

Introduction to Functional Programming in Haskell 1 / 56 Introduction to Functional Programming in Haskell 1 / 56 Outline Why learn functional programming? The essence of functional programming What is a function? Equational reasoning First-order vs. higher-order

More information

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

Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 Principles of Programming Languages Topic: Functional Programming Professor L. Thorne McCarty Spring 2003 CS 314, LS, LTM: Functional Programming 1 Scheme A program is an expression to be evaluated (in

More information

CSCI337 Organisation of Programming Languages LISP

CSCI337 Organisation of Programming Languages LISP Organisation of Programming Languages LISP Getting Started Starting Common Lisp $ clisp i i i i i i i ooooo o ooooooo ooooo ooooo I I I I I I I 8 8 8 8 8 o 8 8 I \ `+' / I 8 8 8 8 8 8 \ `-+-' / 8 8 8 ooooo

More information

Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP)

Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP) Principles of Programming Languages COMP251: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology

More information

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

(Func&onal (Programming (in (Scheme)))) Jianguo Lu (Func&onal (Programming (in (Scheme)))) Jianguo Lu 1 Programming paradigms Func&onal No assignment statement No side effect Use recursion Logic OOP AOP 2 What is func&onal programming It is NOT what you

More information

Freeing memory is a pain. Need to decide on a protocol (who frees what?) Pollutes interfaces Errors hard to track down

Freeing memory is a pain. Need to decide on a protocol (who frees what?) Pollutes interfaces Errors hard to track down Freeing memory is a pain Need to decide on a protocol (who frees what?) Pollutes interfaces Errors hard to track down 1 Freeing memory is a pain Need to decide on a protocol (who frees what?) Pollutes

More information

Discussion 11. Streams

Discussion 11. Streams Discussion 11 Streams A stream is an element and a promise to evaluate the rest of the stream. You ve already seen multiple examples of this and its syntax in lecture and in the books, so I will not dwell

More information