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

Save this PDF as:

Size: px
Start display at page:

## Transcription

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

2 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging list: Pass functions with private data to iterators (map/filter): Done Combine functions (e.g., composition) Currying (multi-arg functions and partial application) Callbacks (e.g., in reactive programming) Implementing an ADT with a record of functions 2

3 Combine functions Canonical example is function composition: (define (compose f g) (lambda (x) (f (g x)))) Creates a closure that remembers what f and g are bound to This function is built-in to Racket; but this definition is basically how it works. 3rd version is the best (clearest as to what it does): (define (sqrt-of-abs i) (sqrt (abs i))) (define (sqrt-of-abs i) ((compose sqrt abs) i)) (define sqrt-of-abs (compose sqrt abs)) 3

4 Currying and Partial Application Currying is the idea of calling a function with an incomplete set of arguments. When you "curry" a function, you get a function back that accepts the remaining arguments. Named after Haskell Curry, who studied related ideas in logic. Useful in situations where you want to call/pass a function, but you don't know the values for all the arguments yet. Ex: a function of two arguments, but coming from two separate places (scopes) in your program. 6

5 Motivation example We want to write code that takes a list of numbers and returns a list of the number 4 raised to the power of each number. in: (x1 x2 xn)! out: (4^x1 4^x2 4^xn)! We could use a lambda expression: (map (lambda (x) (expt 4 x)) lst)! But this can get tedious to do over and over. What if the expt function were defined differently? 7

6 Currying and Partial Application We know (expt x y) raises x to the y'th power. We could define a different version of expt like this: (define (expt-curried x) (lambda (y) (expt x y))! We can call this function like this: ((expt-curried 4) 2)! This is an incredibly flexible definition: We can call with two arguments as normal (with extra parens) Or call with one argument to get a function that accepts the remaining argument. This is critical in some other functional languages (albeit, not Racket or Scheme) where functions may have at most one argument. 8

7 Currying and Partial Application Currying is still useful in Racket with the curry function: Turns a function (f x1 x2 x3 xn) into a function ((((f x1) x2) x3) xn)! curry takes a function f and some optional arguments Returns a function that accumulates remaining arguments until f can be called (all arguments are present). (curry expt 4) == (expt-curried 4)! ((curry expt 4) 2) == ((expt-curried 4) 2)! These can be useful in definitions themselves: (define (double x) (* 2 x))! (define double (curry * 2))! 9

8 Currying and Partial Application Currying is also useful to shorten longish lambda expressions: Old way: (map (lambda (x) (+ x 1)) '(1 2 3))! New way: (map (curry + 1) '(1 2 3))! Great for encapsulating private data: list-ref is the built-in get-nth. (define get-month (curry list-ref '(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)))! This example introduces a new datatype: symbol. Symbols are similar to strings, except they don't have quotes around them (and you can't take them apart or add them together like strings). 10

9 Currying and Partial Application But this gives zero-based months: (define get-month (curry list-ref!! '(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec))) Let's subtract one from the argument first: (define get-month (compose (curry list-ref! '(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec)) (curryr - 1))) curryr curries from right to left, rather than left to right. 11

10 Currying and Partial Application Another example: (define (eval-polynomial coeff x)! (if (null? coeff) 0!! (+ (* (car coeff) (expt x (- (length coeff) 1))) (eval-polynomial (cdr coeff) x))))! (define (make-polynomial coeff)! (lambda (x) (eval-polynomial coeff x)) (define make-polynomial (curry eval-polynomial))! 12

11 Currying and Partial Application A few more examples: (map (compose (curry + 2) (curry * 4)) '(1 2 3))! quadruples then adds two to the list '(1 2 3) (filter (curry < 10) '( ))! Careful! curry works from the left, so (curry < 10) is equivalent to (lambda (x) (< 10 x)) so this filter keeps numbers that are greater than 10. Probably clearer to do: (filter (curryr > 10) '( ))! (In this case, the confusion is because we are used to "<" being an infix operator). 13

12 Return to the foldr J Currying becomes really powerful when you curry higher-order functions. Recall (foldr f init (x1 x2 xn)) returns (f x1 (f x2 (f xn-2 (f xn-1 (f xn init))! (define (sum-list-ok lst) (foldr + 0 lst)) (define sum-list-super-cool (curry foldr + 0) 16

13 Another example Scheme and Racket have andmap and ormap. (andmap f (x1 x2 )) returns (and (f x1) (f x2) )! (ormap f (x1 x2 )) returns (or (f x1) (f x2) )! (andmap (curryr > 7) '(8 9 10)) è #t (ormap (curryr > 7) '( )) è #t (ormap (curryr > 7) '(4 5 6)) è #f (define contains7 (curry ormap (curry = 7))) (define all-are7 (curry andmap (curry = 7))) 17

14 Another example Currying and partial application can be convenient even without higherorder functions. Note: (range a b) returns a list of integers from a to b-1, inclusive. (define (zip lst1 lst2) (if (null? lst1) '() (cons (list (car lst1) (car lst2)) (zip (cdr lst1) (cdr lst2))))) (define countup (curry range 1)) (define (add-numbers lst) (zip (countup (length lst)) lst)) 18

15 When to use currying When you write a lambda function of the form (lambda (y1 y2 ) (f x1 x2 y1 y2 )) You can replace that with (curry f x1 x2 ) Similarly, replace (lambda (y1 y2 ) (f y1 y2 x1 x2 )) with (curryr f x1 x2 ) 19

16 When to use currying Try these: Assuming lst is a list of numbers, write a call to filter that keeps all numbers greater than 4. Assuming lst is a list of lists of numbers, write a call to map that adds a 1 to the front of each sublist. Assuming lst is a list of numbers, write a call to map that turns each number (in lst) into the list (1 number). Assuming lst is a list of numbers, write a call to map that squares each number (you should curry expt). Define a function dist-from-origin in terms of currying a function (dist x1 y1 x2 y2) [assume dist is already defined elsewhere] 20

17 Callbacks A common idiom: Library takes functions to apply later, when an event occurs examples: When a key is pressed, mouse moves, data arrives When the program enters some state (e.g., turns in a game) A library may accept multiple callbacks Different callbacks may need different private data with different types (Can accomplish this in C++ with objects that contain private fields.) 24

18 Mutable state While it s not absolutely necessary, mutable state is reasonably appropriate here We really do want the callbacks registered and events that have been delivered to change due to function calls In "pure" functional programming, there is no mutation. Therefore, it is guaranteed that calling a function with certain arguments will always return the same value, no matter how many times it's called. Not guaranteed once mutation is introduced. This is why global variables are considered "bad" in languages like C or C++ (global constants OK). 25

19 Mutable state: Example in C++ times_called = 0!! int function() { times_called++; return times_called;! }! This is useful, but can cause big problems if somebody else modifies times_called from elsewhere in the program. 26

20 Mutable state Scheme and Racket's variables are mutable. The name of any function which does mutation contains a "!" Mutate a variable with set!! Only works after the variable has been placed into an environment with define, let, or as an argument to a function. set! does not return a value. (define times-called 0)! (define (function) (set! times-called (+ 1 times-called)) times-called)! Notice that functions that have side-effects or use mutation are the only functions that need to have bodies with more than one expression in them. 27

21 Example call-back library Library maintains mutable state for what callbacks are there and provides a function for accepting new ones A real library would support removing them, etc. (define callbacks '()) (define (add-callback func) (set! callbacks (cons func callbacks))) (define (key-press which-key) (for-each (lambda (func) (func which-key)) callbacks)) 29

22 Clients (define (print-if-pressed key message) (add-callback (lambda (which-key) (if (string=? key which-key) (begin (display message) (newline)) #f)))) (define count-presses 0) (add-callback (lambda (key) (set! count-presses (+ 1 count-presses)) (display "total presses = ") (display count-presses) (newline))) 31

23 Improvement on the client side Why clutter up the global environment with count-presses? We don't want some other function mucking with that variable. Let's hide it inside a let that only our callback can access. (let ((count-presses 0)) (add-callback (lambda (key) (set! count-presses (+ 1 count-presses)) (display "total presses = ") (display count-presses) (newline))) 32

24 Implementing an ADT As our last pattern, closures can implement abstract data types They can share the same private data Private data can be mutable or immutable Feels quite a bit like objects, emphasizing that OOP and functional programming have similarities The actual code is advanced/clever/tricky, but has no new features Combines lexical scope, closures, and higher-level functions Client use is not so tricky 33

25 (define (new-stack)! (let ((the-stack '()))! (define (dispatch method-name)! (cond ((eq? method-name 'empty?) empty?)! ((eq? method-name 'push) push)! ((eq? method-name 'pop) pop)! (#t (error "Bad method name"))))! (define (empty?) (null? the-stack))! (define (push item) (set! the-stack (cons item the-stack)))! (define (pop)! (if (null? the-stack) (error "Can't pop an empty stack")! (let ((top-item (car the-stack)))! (set! the-stack (cdr the-stack))! top-item)))! dispatch)) ; this last line is the return value ; of the let statement at the top.! 34

### CS 360 Programming Languages Day 14 Closure Idioms

CS 360 Programming Languages Day 14 Closure Idioms Why lexical scope rocks Last time: currying Today: implementing callbacks and object-oriented programming. Review: mutable state Racket's variables are

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

### CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Fall 2011

CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Fall 2011 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

### CSE341: Programming Languages Lecture 9 Function-Closure Idioms. Dan Grossman Winter 2013

CSE341: Programming Languages Lecture 9 Function-Closure Idioms Dan Grossman Winter 2013 More idioms We know the rule for lexical scope and function closures Now what is it good for A partial but wide-ranging

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

Programming Languages Thunks, Laziness, Streams, Memoization Adapted from Dan Grossman s PL class, U. of Washington You ve been lied to Everything that looks like a function call in Racket is not necessarily

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

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

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

### 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,

### Vectors in Scheme. Data Structures in Scheme

Data Structures in Scheme Vectors in Scheme In Scheme, lists and S-expressions are basic. Arrays can be simulated using lists, but access to elements deep in the list can be slow (since a list is a linked

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

### (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

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

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

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

### Typed Racket: Racket with Static Types

Typed Racket: Racket with Static Types Version 5.1 Sam Tobin-Hochstadt February 14, 2011 Typed Racket is a family of languages, each of which enforce that programs written in the language obey a type system

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

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

### 4/19/2018. Chapter 11 :: Functional Languages

Chapter 11 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken by Alan Turing, Alonzo Church, Stephen

### Scheme as implemented by Racket

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

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

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

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

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

### Functional Programming. Big Picture. Design of Programming Languages

Functional Programming Big Picture What we ve learned so far: Imperative Programming Languages Variables, binding, scoping, reference environment, etc What s next: Functional Programming Languages Semantics

### CS 152 / SE 152 Programming Language Paradigms

CS 152 / SE 152 Programming Language Paradigms Spring Semester 2014 Department of Computer Science San Jose State University Prof. Ron Mak Assignment #3 Assigned: Monday, February 24 Due: Friday, March

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

### Class 6: Efficiency in Scheme

Class 6: Efficiency in Scheme SI 413 - Programming Languages and Implementation Dr. Daniel S. Roche United States Naval Academy Fall 2011 Roche (USNA) SI413 - Class 6 Fall 2011 1 / 10 Objects in Scheme

### regsim.scm ~/umb/cs450/ch5.base/ 1 11/11/13

1 File: regsim.scm Register machine simulator from section 5.2 of STRUCTURE AND INTERPRETATION OF COMPUTER PROGRAMS This file can be loaded into Scheme as a whole. Then you can define and simulate machines

### 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,

### Func%onal Programming in Scheme and Lisp

Func%onal Programming in Scheme and Lisp http://www.lisperati.com/landoflisp/ Overview In a func(onal programming language, func(ons are first class objects You can create them, put them in data structures,

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

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

### Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004

Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004 CS 314, LS,BR,LTM: Scope and Memory 1 Review Functions as first-class objects What can you do with an integer?

### Func%onal Programming in Scheme and Lisp

Func%onal Programming in Scheme and Lisp http://www.lisperati.com/landoflisp/ Overview In a func(onal programming language, func(ons are first class objects You can create them, put them in data structures,

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

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

CSE413: Programming Languages and Implementation Racket structs Implementing languages with interpreters Implementing closures Dan Grossman Fall 2014 Hi! I m not Hal J I love this stuff and have taught

### 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,

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

### 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,

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

CSE 413 Languages & Implementation Hal Perkins Winter 2019 Structs, Implementing Languages (credits: Dan Grossman, CSE 341) 1 Goals Representing programs as data Racket structs as a better way to represent

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

### Racket: Modules, Contracts, Languages

Racket: Modules, Contracts, Languages Advanced Functional Programming Jean-Noël Monette November 2013 1 Today Modules are the way to structure larger programs in smaller pieces. Modules can import and

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

### 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,

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

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

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

### Normal Order (Lazy) Evaluation SICP. Applicative Order vs. Normal (Lazy) Order. Applicative vs. Normal? How can we implement lazy evaluation?

Normal Order (Lazy) Evaluation Alternative models for computation: Normal (Lazy) Order Evaluation Memoization Streams Applicative Order: evaluate all arguments, then apply operator Normal Order: pass unevaluated

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

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 18: Functional Programming Zheng (Eddy) Zhang Rutgers University April 9, 2018 Review: Defining Scheme Functions (define ( lambda (

### Introduction to Functional Programming in Racket. CS 550 Programming Languages Jeremy Johnson

Introduction to Functional Programming in Racket CS 550 Programming Languages Jeremy Johnson 1 Objective To introduce functional programming in racket Programs are functions and their semantics involve

### Notes on Higher Order Programming in Scheme. by Alexander Stepanov

by Alexander Stepanov August 1986 INTRODUCTION Why Scheme? Because it allows us to deal with: 1. Data Abstraction - it allows us to implement ADT (abstact data types) in a very special way. The issue of

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

### Lambda Calculus and Lambda notation in Lisp II. Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky.

λ Calculus Basis Lambda Calculus and Lambda notation in Lisp II Based on Prof. Gotshalks notes on Lambda Calculus and Chapter 9 in Wilensky Mathematical theory for anonymous functions» functions that have

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

### 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.

### Extensible Pattern Matching

Extensible Pattern Matching Sam Tobin-Hochstadt PLT @ Northeastern University IFL, September 3, 2010 Extensible Pattern Matching in an Extensible Language Sam Tobin-Hochstadt PLT @ Northeastern University

### Dictionaries. Looking up English words in the dictionary. Python sequences and collections. Properties of sequences and collections

Looking up English words in the dictionary Comparing sequences to collections. Sequence : a group of things that come one after the other Collection : a group of (interesting) things brought together for

### CSE341, Spring 2013, Final Examination June 13, 2013

CSE341, Spring 2013, Final Examination June 13, 2013 Please do not turn the page until 8:30. Rules: The exam is closed-book, closed-note, except for both sides of one 8.5x11in piece of paper. Please stop

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

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

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

### High Performance Computing

High Performance Computing MPI and C-Language Seminars 2009 Photo Credit: NOAA (IBM Hardware) High Performance Computing - Seminar Plan Seminar Plan for Weeks 1-5 Week 1 - Introduction, Data Types, Control

### 4.2 Variations on a Scheme -- Lazy Evaluation

[Go to first, previous, next page; contents; index] 4.2 Variations on a Scheme -- Lazy Evaluation Now that we have an evaluator expressed as a Lisp program, we can experiment with alternative choices in

### CSc 520 Principles of Programming Languages

CSc 520 Principles of Programming Languages 9: Scheme Metacircular Interpretation Christian Collberg collberg@cs.arizona.edu Department of Computer Science University of Arizona Copyright c 2005 Christian

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

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

### Lecture Notes on Lisp A Brief Introduction

Why Lisp? Lecture Notes on Lisp A Brief Introduction Because it s the most widely used AI programming language Because Prof Peng likes using it Because it s good for writing production software (Graham

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

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

### CS 440: Programming Languages and Translators, Spring 2019 Mon

Haskell, Part 4 CS 440: Programming Languages and Translators, Spring 2019 Mon 2019-01-28 More Haskell Review definition by cases Chapter 6: Higher-order functions Revisit currying map, filter Unnamed

### Sample Final Exam Questions

91.301, Organization of Programming Languages Fall 2015, Prof. Yanco Sample Final Exam Questions Note that the final is a 3 hour exam and will have more questions than this handout. The final exam will

### Turtles All The Way Down

Turtles All The Way Down Bertrand Russell had just finished giving a public lecture on the nature of the universe. An old woman said Prof. Russell, it is well known that the earth rests on the back of

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

1 A couple of Functions 1 Let's take another example of a simple lisp function { one that does insertion sort. Let us assume that this sort function takes as input a list of numbers and sorts them in ascending

### Lecture 4: Higher Order Functions

Lecture 4: Higher Order Functions Søren Haagerup Department of Mathematics and Computer Science University of Southern Denmark, Odense September 26, 2017 HIGHER ORDER FUNCTIONS The order of a function

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

### OCaml Language Choices CMSC 330: Organization of Programming Languages

OCaml Language Choices CMSC 330: Organization of Programming Languages! Implicit or explicit declarations?! Explicit variables must be introduced with let before use! But you don t need to specify types

### Parsing Scheme (+ (* 2 3) 1) * 1

Parsing Scheme + (+ (* 2 3) 1) * 1 2 3 Compiling Scheme frame + frame halt * 1 3 2 3 2 refer 1 apply * refer apply + Compiling Scheme make-return START make-test make-close make-assign make- pair? yes

### CSE 341: Programming Languages

CSE 341: Programming Languages Winter 2005 Lecture 17 varargs and apply, implementing higher-order functions CSE341 Winter 2005, Lecture 17 1 Today: Some easy Scheme odds and ends Implementing higher-order

### A LISP Interpreter in ML

UNIVERSITY OF OSLO Department of Informatics A LISP Interpreter in ML Mandatory Assignment 1 INF3110 September 21, 2009 Contents 1 1 Introduction The purpose of this assignment is to write an interpreter,

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

### CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

CS113: Lecture 3 Topics: Variables Data types Arithmetic and Bitwise Operators Order of Evaluation 1 Variables Names of variables: Composed of letters, digits, and the underscore ( ) character. (NO spaces;

### An introduction to Scheme

An introduction to Scheme Introduction A powerful programming language is more than just a means for instructing a computer to perform tasks. The language also serves as a framework within which we organize

### Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Booleans and Short-Circuit Evaluation. Tuples as Values.

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Elsa L Gunter 2112 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421d # true;; - : bool = true # false;; - : bool =

### TAIL RECURSION, SCOPE, AND PROJECT 4 11

TAIL RECURSION, SCOPE, AND PROJECT 4 11 COMPUTER SCIENCE 61A Noveber 12, 2012 1 Tail Recursion Today we will look at Tail Recursion and Tail Call Optimizations in Scheme, and how they relate to iteration

### Local definitions and lexical scope

Local definitions and lexical scope Readings: HtDP, Intermezzo 3 (Section 18). Language level: Intermediate Student CS 135 Winter 2018 09: Local definitions and lexical scope 1 Local definitions The functions

### Local definitions and lexical scope. Local definitions. Motivating local definitions. s(s a)(s b)(s c), where s = (a + b + c)/2.

Local definitions and lexical scope Readings: HtDP, Intermezzo 3 (Section 18). Language level: Intermediate Student CS 135 Winter 2018 09: Local definitions and lexical scope 1 Local definitions The functions

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:

### How to Design Programs

How to Design Programs How to (in Racket): represent data variants trees and lists write functions that process the data See also http://www.htdp.org/ 1 Running Example: GUIs Pick a fruit: Apple Banana

### The Haskell HOP: Higher-order Programming

The Haskell HOP: Higher-order Programming COS 441 Slides 6 Slide content credits: Ranjit Jhala, UCSD Agenda Haskell so far: First-order functions This time: Higher-order functions: Functions as data, arguments

### CS61A Midterm 2 Review (v1.1)

Spring 2006 1 CS61A Midterm 2 Review (v1.1) Basic Info Your login: Your section number: Your TA s name: Midterm 2 is going to be held on Tuesday 7-9p, at 1 Pimentel. What will Scheme print? What will the

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

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

Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic expressions. Symbolic manipulation: you do it all the

### Chapter 15 Functional Programming Languages

Chapter 15 Functional Programming Languages Fundamentals of Functional Programming Languages Introduction to Scheme A programming paradigm treats computation as the evaluation of mathematical functions.

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

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