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

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

(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

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

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

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

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

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,

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

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

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

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

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

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

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

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

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

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,

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

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

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

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 =

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 SCHEME. 1 What Would Scheme Print? COMPUTER SCIENCE MENTORS 61A. October 30 to November 3, Solution: Solutions begin on the following page.

MORE SCHEME COMPUTER SCIENCE MENTORS 61A October 30 to November 3, 2017 1 What Would Scheme Print? Solutions begin on the following page. 1. What will Scheme output? Draw box-and-pointer diagrams to help

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

Sequentialising a concurrent program using continuation-passing style

Sequentialising a concurrent program using continuation-passing style Juliusz Chroboczek Université de Paris-Diderot (Paris 7) jch@pps.jussieu.fr 28 January 2012 1/44 Outline Everything you ever wanted

ECSE 321 Assignment 2

ECSE 321 Assignment 2 Instructions: This assignment is worth a total of 40 marks. The assignment is due by noon (12pm) on Friday, April 5th 2013. The preferred method of submission is to submit a written

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

CS152: Programming Languages Lecture 7 Lambda Calculus Dan Grossman Spring 2011 Where we are Done: Syntax, semantics, and equivalence For a language with little more than loops and global variables Now:

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

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

Whereweare CS-XXX: Graduate Programming Languages Lecture 7 Lambda Calculus Done: Syntax, semantics, and equivalence For a language with little more than loops and global variables Now: Didn t IMP leave

Project 1: Part 1. x = b± b 2 4ac., x 2 = b b 2 4ac.

Project 1: Part 1 Project 1 will be to calculate orthogonal polynomials. It will have several parts. Note: The scheme code in this writeup is available in the file project1.scm, available from the course

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

Scheme Basics > (butfirst '(help!)) () [The butfirst of a *sentence* containing one word is all but that word, i.e., the empty sentence. (BUTFIRST 'HELP!) without the inner parentheses would be butfirst

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

CMSC330. Objects, Functional Programming, and lambda calculus

CMSC330 Objects, Functional Programming, and lambda calculus 1 OOP vs. FP Object-oriented programming (OOP) Computation as interactions between objects Objects encapsulate mutable data (state) Accessed

The Typed Racket Guide

The Typed Racket Guide Version 6.9 Sam Tobin-Hochstadt ăsamth@racket-lang.orgą, Vincent St-Amour ăstamourv@racket-lang.orgą, Eric Dobson ăendobson@racket-lang.orgą, and Asumu Takikawa ăasumu@racket-lang.orgą

CS Programming I: Arrays

CS 200 - Programming I: Arrays Marc Renault Department of Computer Sciences University of Wisconsin Madison Fall 2017 TopHat Sec 3 (PM) Join Code: 719946 TopHat Sec 4 (AM) Join Code: 891624 Array Basics

The String Class Represents a character string (e.g. "Hi") Implicit constructor: String quote = "Hello World"; string literal All string literals are String instances Object has a tostring() method More

CSci 4223 Principles of Programming Languages

CSci 4223 Principles of Programming Languages Lecture 11 Review Features learned: functions, tuples, lists, let expressions, options, records, datatypes, case expressions, type synonyms, pattern matching,

Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP)

Fundamentals of Artificial Intelligence COMP221: Functional Programming in Scheme (and LISP) Prof. Dekai Wu Department of Computer Science and Engineering The Hong Kong University of Science and Technology

CS Lecture 6: Map and Fold. Prof. Clarkson Spring Today s music: Selections from the soundtrack to 2001: A Space Odyssey

CS 3110 Lecture 6: Map and Fold Prof. Clarkson Spring 2015 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Course so far: Syntax and semantics of (most of) OCaml Today: No

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

CSCE 314 Programming Languages

CSCE 314 Programming Languages Haskell 101 Dr. Hyunyoung Lee 1 Contents 1. Historical Background of Haskell 2. Lazy, Pure, and Functional Language 3. Using ghc and ghci 4. Functions 5. Haskell Scripts

STREAMS 10. Basics of Streams. Practice with Streams COMPUTER SCIENCE 61AS. 1. What is a stream? 2. How does memoization work?

STREAMS 10 COMPUTER SCIENCE 61AS Basics of Streams 1. What is a stream? 2. How does memoization work? 3. Is a cons-stream a special form? Practice with Streams 1. Define a procedure (ones) that, when run

Expression Values Operators. (string-append a b c ) a, b, c string-append. (substring abcd 0 2) abcd, 0, 2 substring

Expressions Expression Values perators (+ 2 3 5) 2 3 5 + (* 3.1 2.5) 3.1, 2.5 * (+ (* 3 2.2) 7) 7, 6.6 *, + (string-append a b c ) a, b, c string-append (circle 20 solid red ) 20, solid, red circle (substring

More BSTs & AVL Trees bstdelete

More BSTs & AVL Trees bstdelete if (key not found) return else if (either subtree is empty) { delete the node replacing the parents link with the ptr to the nonempty subtree or NULL if both subtrees are

Robot Programming with Lisp

4. Functional Programming: Higher-order Functions, Map/Reduce, Lexical Scope Institute for Artificial University of Bremen 9 of November, 2017 Functional Programming Pure functional programming concepts

Racket: Macros. Advanced Functional Programming. Jean-Noël Monette. November 2013

Racket: Macros Advanced Functional Programming Jean-Noël Monette November 2013 1 Today Macros pattern-based macros Hygiene Syntax objects and general macros Examples 2 Macros (According to the Racket Guide...)

Building a system for symbolic differentiation

Computer Science 21b Structure and Interpretation of Computer Programs Building a system for symbolic differentiation Selectors, constructors and predicates: (constant? e) Is e a constant? (variable? e)

So far, we have seen two different approaches for using computing to solve problems:

Chapter 10 Objects By the word operation, we mean any process which alters the mutual relation of two or more things, be this relation of what kind it may. This is the most general definition, and would

Data Types. 9. Types. a collection of values and the definition of one or more operations that can be performed on those values

Data Types 1 data type: a collection of values and the definition of one or more operations that can be performed on those values C++ includes a variety of built-in or base data types: short, int, long,

Introduction to Concepts in Functional Programming. CS16: Introduction to Data Structures & Algorithms Spring 2017

Introduction to Concepts in Functional Programming CS16: Introduction to Data Structures & Algorithms Spring 2017 Outline Functions State Functions as building blocks Higher order functions Map Reduce

6.001, Spring Semester, 1998, Final Exam Your Name: 2 Question 1 (12 points): Each of the parts below should be treated as independent. For each part,

1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.001 Structure and Interpretation of Computer Programs Spring Semester, 1998, Final Exam Your Name: Open

Polycom Advantage Service Endpoint Utilization Report

Polycom Advantage Service Endpoint Utilization Report ABC Company 3/1/2016-3/31/2016 Polycom, Inc. All rights reserved. SAMPLE REPORT d This report is for demonstration purposes only. Any resemblance to

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

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

Fall 2017 December 4, 2017

CS 61A Final Review Fall 2017 December 4, 2017 Instructions Form a small group. Start on the first problem. Check off with a helper or discuss your solution process with another group once everyone understands

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

If Case Loop Next Exit

If Case Loop Next Exit If statement If_statement ::= if condition then sequence of sequential statements {elsif condition then sequence of sequential statements} [else sequence of sequential statements]

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

CS 480 Lisp J. Kosecka George Mason University Lisp Slides Symbolic Programming Symbols: +, -, 1, 2 etc. Symbolic expressions: (+ 1 2), (+ (* 3 4) 2) Symbolic programs are programs that manipulate symbolic

# true;; - : bool = true. # false;; - : bool = false 9/10/ // = {s (5, "hi", 3.2), c 4, a 1, b 5} 9/10/2017 4

Booleans (aka Truth Values) Programming Languages and Compilers (CS 421) Sasa Misailovic 4110 SC, UIUC https://courses.engr.illinois.edu/cs421/fa2017/cs421a # true;; - : bool = true # false;; - : bool

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

e-sens Nordic & Baltic Area Meeting Stockholm April 23rd 2013

e-sens Nordic & Baltic Area Meeting Stockholm April 23rd 2013 Objectives of the afternoon parallel tracks sessions 2 Meeting objectives High level: Identification of shared interests with emphasis on those

ICT PROFESSIONAL MICROSOFT OFFICE SCHEDULE MIDRAND

ICT PROFESSIONAL MICROSOFT OFFICE SCHEDULE MIDRAND BYTES PEOPLE SOLUTIONS Bytes Business Park 241 3rd Road Halfway Gardens Midrand Tel: +27 (11) 205-7000 Fax: +27 (11) 205-7110 Email: gauteng.sales@bytes.co.za

The Art of Recursion: Problem Set 10

The Art of Recursion: Problem Set Due Tuesday, November Tail recursion A recursive function is tail recursive if every recursive call is in tail position that is, the result of the recursive call is immediately

Pattern Matching for Scheme

Pattern Matching for Scheme Andrew K. Wright March 1996 Department of Computer Science MS 132 Rice University 6100 Main Street Houston, Texas 77005-1892 Contents 1 Match 1 1.1 Definition... 1 1.1.1 Patterns...

low and not larger than high. 18 points

CSE 330 Test 1 (1 point) Spring 015 Multiple Choice. Write your answer to the LEFT of each problem. 3 points each 1. Lisp was invented at: A. IBM B. MIT C. Netscape D. Stanford. In C++, what operator is

9 Objects and Classes

9 Objects and Classes Many programming tasks require the program to manage some piece of state through an interface. For example, a file system has internal state, but we access and modify that state only

Lecture 16. Reading: Weiss Ch. 5 CSE 100, UCSD: LEC 16. Page 1 of 40

Lecture 16 Hashing Hash table and hash function design Hash functions for integers and strings Collision resolution strategies: linear probing, double hashing, random hashing, separate chaining Hash table

CS Lecture 6: Map and Fold. Prof. Clarkson Fall Today s music: Selections from the soundtrack to 2001: A Space Odyssey

CS 3110 Lecture 6: Map and Fold Prof. Clarkson Fall 2014 Today s music: Selections from the soundtrack to 2001: A Space Odyssey Review Features so far: variables, operators, let expressions, if expressions,

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

Resources matter. Orders of Growth of Processes. R(n)= (n 2 ) Orders of growth of processes. Partial trace for (ifact 4) Partial trace for (fact 4)

Orders of Growth of Processes Today s topics Resources used by a program to solve a problem of size n Time Space Define order of growth Visualizing resources utilization using our model of evaluation Relating

PROGRAMMING IN HASKELL. Chapter 2 - First Steps

PROGRAMMING IN HASKELL Chapter 2 - First Steps 0 The Hugs System Hugs is an implementation of Haskell 98, and is the most widely used Haskell system; The interactive nature of Hugs makes it well suited

CIS192: Python Programming

CIS192: Python Programming Functions and Functional Programming Harry Smith University of Pennsylvania January 25, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 3 January 25, 2018 1 / 39

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

Chapter 9 Technicalities: Classes

Chapter 9 Technicalities: Classes Bjarne Stroustrup www.stroustrup.com/programming Abstract This lecture presents language technicalities, mostly related to user defined types; that is, classes and enumerations.

Functions and Recursion. Dr. Philip Cannata 1

Functions and Recursion Dr. Philip Cannata 1 10 High Level Languages This Course Java (Object Oriented) Jython in Java Relation ASP RDF (Horn Clause Deduction, Semantic Web) Dr. Philip Cannata 2 let transformation,

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

WEB 2.0 & EAST ASIAN LIBRARIANS JIANG, SHUYONG

WEB 2.0 & EAST ASIAN LIBRARIANS JIANG, SHUYONG ALA-AAMES June 27, 2010 Washington D.C. East Asian Librarian Survey on Using Web 2.0 Tools It is to know how and what web 2.0 tools are used in promoting

Imperative programming in F#

Imperative programming in F# Björn Lisper School of Innovation, Design, and Engineering Mälardalen University bjorn.lisper@mdh.se http://www.idt.mdh.se/ blr/ Imperative programming in F# (revised 2015-05-05)

Mpoli Archive - FTP Site Statistics. Top 20 Directories Sorted by Disk Space

Mpoli Archive - FTP Site Statistics Property Value FTP Server ftp.mpoli.fi Description Mpoli Archive Country Finland Scan Date 01/Nov/2015 Total Dirs 52,408 Total Files 311,725 Total Data 28.53 GB Top

How It All Stacks Up - or - Bar Charts with Plotly. ISC1057 Janet Peterson and John Burkardt Computational Thinking Fall Semester 2016

* How It All Stacks Up - or - Bar Charts with Plotly ISC1057 Janet Peterson and John Burkardt Computational Thinking Fall Semester 2016 In a game of poker, players bet by tossing chips into the center

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

CSC148 Intro. to Computer Science Lecture 3: designing classes, special methods, composition, inheritance, Stack, Sack Amir H. Chinaei, Summer 2016 Office Hours: R 10-12 BA4222 ahchinaei@cs.toronto.edu

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

A Brief Introduction to Scheme (I)

A Brief Introduction to Scheme (I) Philip W. L. Fong pwlfong@cs.uregina.ca Department of Computer Science University of Regina Regina, Saskatchewan, Canada Scheme Scheme I p.1/44 Scheme: Feature Set A

Contract-based Programming in Ada 2012 A Tutorial

Contract-based Programming in Ada 2012 A tutorial on how to use the Ada 2012 features for specifying detailed, checked contracts for types and subprograms 1. Contracts document constraints on how types

Code example: sfact SICP Explicit-control evaluator. Example register machine: instructions. Goal: a tail-recursive evaluator.

6.001 SICP Explicit-control evaluator Big ideas: how to connect evaluator to machine instructions how to achieve tail recursion Obfuscation: tightly optimized instruction sequence Background eval-dispatch

CS61A Notes 02b Fake Plastic Trees. 2. (cons ((1 a) (2 o)) (3 g)) 3. (list ((1 a) (2 o)) (3 g)) 4. (append ((1 a) (2 o)) (3 g))

CS61A Notes 02b Fake Plastic Trees Box and Pointer Diagrams QUESTIONS: Evaluate the following, and draw a box-and-pointer diagram for each. (Hint: It may be easier to draw the box-and-pointer diagram first.)

Allegro CL Certification Program

Allegro CL Certification Program Lisp Programming Series Level I Review David Margolies 1 Summary 1 A lisp session contains a large number of objects which is typically increased by user-created lisp objects

CIS192 Python Programming

CIS192 Python Programming Functional Programming Eric Kutschera University of Pennsylvania January 30, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 January 30, 2015 1 / 31 Questions Homework

Fast Lookup: Hash tables

CSE 100: HASHING Operations: Find (key based look up) Insert Delete Fast Lookup: Hash tables Consider the 2-sum problem: Given an unsorted array of N integers, find all pairs of elements that sum to a

Lecture 21: Functional Programming in Python. List Comprehensions

The University of North Carolina at Chapel Hill Spring 2002 Lecture 21: Functional Programming in March 1 1 List Comprehensions Haskell Lists can be defined by enumeration using list comprehensions Syntax:

CSE 341: Programming Languages

CSE 341: Programming Languages Dan Grossman Spring 2008 Lecture 6 Nested pattern-matching; course motivation Dan Grossman CSE341 Spring 2008, Lecture 6 1 Patterns What we know: case-expresssions do pattern-matching