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

Similar documents
CSE341: Programming Languages Winter 2018 Unit 5 Summary Zach Tatlock, University of Washington

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures

CS 314 Principles of Programming Languages

CSCC24 Functional Programming Scheme Part 2

CSE 413 Languages & Implementation. Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341)

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

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

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Dan Grossman Fall 2011

Functional Programming. Pure Functional Languages

Functional Programming. Pure Functional Languages

CS 314 Principles of Programming Languages

CSE341: Programming Languages Lecture 17 Implementing Languages Including Closures. Dan Grossman Autumn 2018

Concepts of programming languages

Programming Languages. Thunks, Laziness, Streams, Memoization. Adapted from Dan Grossman s PL class, U. of Washington

CSE341: Programming Languages Lecture 4 Records, Datatypes, Case Expressions. Dan Grossman Spring 2013

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

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

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

CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Dan Grossman Winter 2013

Ruby logistics. CSE341: Programming Languages Lecture 19 Introduction to Ruby and OOP. Ruby: Not our focus. Ruby: Our focus. A note on the homework

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Zach Tatlock Winter 2018

Function definitions. CSE341: Programming Languages Lecture 2 Functions, Pairs, Lists. Example, extended. Some gotchas. Zach Tatlock Winter 2018

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

Organization of Programming Languages CS3200/5200N. Lecture 11

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

CSE 341: Programming Languages

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

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

Typical workflow. CSE341: Programming Languages. Lecture 17 Implementing Languages Including Closures. Reality more complicated

CSE 341, Autumn 2015, Ruby Introduction Summary

CS422 - Programming Language Design

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

Closures. Mooly Sagiv. Michael Clarkson, Cornell CS 3110 Data Structures and Functional Programming

A Second Look At ML. Chapter Seven Modern Programming Languages, 2nd ed. 1

Functional Programming - 2. Higher Order Functions

CSE341: Programming Languages Lecture 15 Macros. Zach Tatlock Winter 2018

What is a macro. CSE341: Programming Languages Lecture 15 Macros. Example uses. Using Racket Macros. Zach Tatlock Winter 2018

CSE 341 : Programming Languages

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

Introduction to Scheme

Test 1 Summer 2014 Multiple Choice. Write your answer to the LEFT of each problem. 5 points each 1. Preprocessor macros are associated with: A. C B.

CSE341 Autumn 2017, Final Examination December 12, 2017

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

User-defined Functions. Conditional Expressions in Scheme

Functional Languages. CSE 307 Principles of Programming Languages Stony Brook University

CSE341: Programming Languages Lecture 7 First-Class Functions. Dan Grossman Winter 2013

CSE 341: Programming Languages

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

CS 314 Principles of Programming Languages

Functional Programming. Big Picture. Design of Programming Languages

CS152: Programming Languages. Lecture 7 Lambda Calculus. Dan Grossman Spring 2011

Scheme as implemented by Racket

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

LECTURE 16. Functional Programming

CSE 341: Programming Languages

Functional Programming Lecture 1: Introduction

CSC324 Functional Programming Efficiency Issues, Parameter Lists

An Introduction to Scheme

Scheme: Expressions & Procedures

Lisp. Versions of LISP

Typed Racket: Racket with Static Types

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

Programming Languages

Project 2: Scheme Interpreter

Programming Languages

Lambda Calculus see notes on Lambda Calculus

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

Functional abstraction

CSE 341 Section 7. Eric Mullen Spring Adapted from slides by Nicholas Shahan, Dan Grossman, and Tam Dang

Typed Scheme: Scheme with Static Types

CSE341 Spring 2016, Final Examination June 6, 2016

Programming Languages. Streams Wrapup, Memoization, Type Systems, and Some Monty Python

CSE341, Spring 2013, Final Examination June 13, 2013

Whereweare. CS-XXX: Graduate Programming Languages. Lecture 7 Lambda Calculus. Adding data structures. Data + Code. What about functions

Functional Programming

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

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

The Typed Racket Guide

CS 275 Name Final Exam Solutions December 16, 2016

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

CS251 Programming Languages Handout # 47 Prof. Lyn Turbak May 22, 2005 Wellesley College. Scheme

CSE341 Spring 2017, Final Examination June 8, 2017

CSE341 Spring 2017, Final Examination June 8, 2017

CMSC 330: Organization of Programming Languages. OCaml Expressions and Functions

The Environment Model. Nate Foster Spring 2018

CSE 341: Programming Languages

CSE 341 Section 7. Ethan Shea Autumn Adapted from slides by Nicholas Shahan, Dan Grossman, Tam Dang, and Eric Mullen

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

CSE 505: Concepts of Programming Languages

Functional Programming. Pure Functional Programming

TAIL RECURSION, SCOPE, AND PROJECT 4 11

CS 314 Principles of Programming Languages. Lecture 16

CONCEPTS OF PROGRAMMING LANGUAGES Solutions for Mid-Term Examination

Lists. Prof. Clarkson Fall Today s music: "Blank Space" by Taylor Swift

CS 360 Programming Languages Interpreters

Functional programming in LISP

News. Programming Languages. Complex types: Lists. Recap: ML s Holy Trinity. CSE 130: Spring 2012

CS 11 Haskell track: lecture 1

CS 342 Lecture 6 Scheme Procedures and Closures By: Hridesh Rajan

Transcription:

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 4 Introduction to Racket Dan Grossman Fall 20 Like ML, functional focus with imperative features Anonymous functions, closures, no return statement, etc. But doesn t rely on pattern-matching Unlike ML, no static type system: accepts more programs, but most errors do not occur until run-time Really minimalist syntax Advanced features like macros, modules, quoting/eval, continuations, contracts, Will do only a couple of these 2 Racket vs. Scheme Getting started Scheme and Racket are very similar languages Racket changed its name in 200 Notes and instructor may occasionally slip up Racket made some non-backward-compatible changes How the empty list is written Cons cells not mutable How modules work Etc. and many additions Result: A modern language used to build some real systems More of a moving target (notes may become outdated) Online documentation, particular The Racket Guide 3 DrRacket definitions window and interactions window very similar to how we used emacs and a REPL DrRacket has always focused on good-for-teaching See usage notes for how to use REPL, testing files, etc. You need to get good at learning new tools on your own, but today s demos (more code than in slides) will help Start every file with a line containing only #lang racket (Can have comments before this, but not code) A file is a module containing a collection of definitions (bindings) 4 #lang racket (define x 3) (define y (+ x 2)) (define cube ; function (* x (* x x)))) (define pow ; recursive function (lambda (x y) (* x (pow x (- y )))))) 5 Some niceties Many built-in functions (a.k.a. procedures) take any number of args Yes * is just a function Yes we ll show you later how to define variable-arity functions (define cube (* x x x))) Better style for non-anonymous function definitions (just sugar): (define (cube x) (* x x x)) (define (pow x y) (* x (pow x (- y ))))) 6

Old-friend #: currying Currying is an idiom that works in any language with closures Less common in Racket because it has real multiple args (define pow (lambda (y) (* x ((pow x) (- y ))))))) (define three-to-the (pow 3)) (define eightyone (three-to-the 4)) (define sixteen ((pow 2) 4)) Sugar for defining curried functions: (No sugar for calling curried functions) (define ((pow x) y) (if 7 Old-friend #2: List processing Empty list: null (unlike Scheme, () doesn t work, but '() does) Cons constructor: cons (also (list e en) is convenient) Access head of list: car (car and cdr a historical accident) Access tail of list: cdr Check for empty: null? s: 0 (+ (car xs) (sum (cdr xs))))) (define (my-append xs ys) ys (cons (car xs) (my-append (cdr xs) ys)))) 8 Racket syntax Why is this good? Ignoring a few bells and whistles, Racket has an amazingly simple syntax A term (anything in the language) is either: An atom, e.g., #t, #f, 34, "hi", null, 4.0, x, A special form, e.g., define, lambda, if Macros will let us define our own A sequence of terms in parens: (t t2 tn) Note: Can use [ anywhere you use (, but must match with ] Will see shortly places where [ ] is common style DrRacket lets you type ) and replaces it with ] to match 9 By parenthesizing everything, converting the program text into a tree representing the program (parsing) is trivial and unambiguous Atoms are leaves Sequences are nodes with elements as children (No other rules) Also makes indentation easy define : (define cube (* x x x))) cube lambda x * x x Contrast CSE42 s obsession with expression precedence 0 x Parenthesis bias If you look at the HTML for a web page, it takes the same approach: (foo written <foo> ) written </foo> But for some reason, LISP/Scheme/Racket is the target of subjective parenthesis-bashing Bizarrely, often by people who have no problem with HTML You are entitled to your opinion about syntax, but a good historian wouldn t refuse to study a country where he/she didn t like people s accents http://xkcd.com/297/ LISP invented around 959 by John McCarthy (9/4/27-0/23/20) Invented garbage collection 2

Parentheses matter You must break yourself of one habit for Racket: Do not add/remove parens because you feel like it Parens are never optional or meaningless!!! In most places (e) means call e with zero arguments So ((e)) means call e with zero arguments and call the result with zero arguments Without static typing, often get hard-to-diagnose run-time errors Correct: (define (fact n)(if (= n 0) (* n (fact (- n ))))) Treats as a zero-argument function (run-time error): (define (fact n)(if (= n 0) ()(* n (fact (- n ))))) Gives if 5 arguments (syntax error) (define (fact n)(if = n 0 (* n (fact (- n ))))) 3 arguments to define (including (n)) (syntax error) (define fact (n)(if (= n 0) (* n (fact (- n ))))) Treats n as a function, passing it * (run-time error) (define (fact n)(if (= n 0) (n * (fact (- n ))))) 3 4 Dynamic typing Will spend a later lecture contrasting static typing (e.g., ML) with dynamic typing (e.g., Racket) For now: Frustrating not to catch little errors like (n * x) until you test your function But can use very flexible data structures and code without convincing a type checker that it makes sense : A list that can contain numbers or other lists Assuming lists or numbers all the way down, sum all the numbers 0 (if (number? (car xs)) (+ (car xs) (sum (cdr xs))) (+ (sum (car xs)) (sum (cdr xs)))))) No need for a fancy datatype binding, constructors, etc. Works no matter how deep the lists go But assumes each element is a list or a number Will get a run-time error if anything else is encountered 5 6 Better style A variation Avoid nested if-expressions when you can use cond-expressions instead Can think of one as sugar for the other General syntax: (cond [ea eb] [e2a e2b] [ena enb]) Good style: ena should be #t : (cond [(null? xs) 0] [(number? (car xs)) (+ (car xs) (sum (cdr xs)))] [#t (+ (sum (car xs)) (sum (cdr xs)))])) 7 We could change our spec to say instead of errors on nonnumbers, we should just ignore them (same as adding 0) So this version can work for any argument in all of Racket will never raise an error Compare carefully, we did not just add a branch (define (sum arg) (cond [(null? arg) 0] [(number? arg) arg] [(list? arg) (+ (sum (car arg)) (sum (cdr arg)))] [#t 0])) 8

Local bindings Let Racket has 4 ways to define local variables let let* letrec define Variety is good: They have different semantics Use the one most convenient for your needs, which helps communicate your intent to people reading your code If any will work, use let Will help us better learn scope and environments Like in ML, the 3 kinds of let-expressions can appear anywhere A let expression can bind any number of local variables Notice where all the parentheses are The expressions are all evaluated in the environment from before the let-expression Except the body can use all the local variables of course This is not how ML let-expressions work Convenient for things like (let ([x y][y x]) ) (define (silly-double x) (let ([x (+ x 3)] [y (+ x 2)]) (+ x y -5))) 9 20 Let* Syntactically, a let* expression is a let-expression with more character The expressions are evaluated in the environment produced from the previous bindings Can repeat bindings (later ones shadow) This is how ML let-expressions work (define (silly-double x) (let* ([x (+ x 3)] [y (+ x 2)]) (+ x y -8))) 2 Letrec Syntactically, a letrec expression is also the same The expressions are evaluated in the environment that includes all the bindings (define (silly-triple x) (letrec ([y (+ x 2)] [f (lambda(z) (+ z y w x))] [w (+ x 7)]) (f -9))) Needed for mutual recursion But expressions are still evaluated in order: accessing an uninitialized binding would produce #<undefined> Would be bad style and surely a bug Remember function bodies not evaluated until called 22 More letrec Letrec is ideal for recursion (including mutual recursion) (define (silly-mod2 x) (letrec ([even? ( (x)(if (zero? x) #t (odd? (- x ))))] [odd? ( (x)(if (zero? x) #f (even? (- x ))))]) (if (even? x) 0 ))) Do not use later bindings except inside functions This example will return #<undefined> if x is true (By the way, everything is true except #f) (define (bad-letrec x) (letrec ([y z] [z 3]) (if x y z))) 23 Local defines In certain positions, like the beginning of function bodies, you can put defines For defining local variables, same semantics as letrec (define (silly-mod2 x) (define (even? x)(if (zero? x) #t (odd? (- x )))) (define (odd? x) (if (zero? x) #f (even?(- x )))) (if (even? x) 0 )) 24

Top-level The bindings in a file / module work like local defines, i.e., letrec Like ML, you can refer to earlier bindings Unlike ML, you can refer to later bindings But refer to later bindings only in function bodies Detail: Will get an error instead of #<undefined> Unlike ML, cannot define the same variable twice in module Would make no sense; can t have both in environment If each file is its own module, what is externally visible and how do you refer to bindings in other files? Later lecture See usage notes for a way to test homework from a second file 25