Func%onal Programming in Scheme and Lisp

Similar documents
Func%onal Programming in Scheme and Lisp

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

Lists in Lisp and Scheme

CS 360 Programming Languages Interpreters

Introduction to Functional Programming

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

Lecture Notes on Lisp A Brief Introduction

Chapter 15 Functional Programming Languages

Functional Programming. Pure Functional Programming

Racket Values. cons Glues Two Values into a Pair. The Pros of cons: Pairs and Lists in Racket. Box-and-pointer diagrams for cons trees

FP Foundations, Scheme

Racket Values. cons Glues Two Values into a Pair. The Pros of cons: Programming with Pairs and Lists. Box-and-pointer diagrams for cons trees

Ways to implement a language

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

User-defined Functions. Conditional Expressions in Scheme

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

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

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

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

Functional Programming. Big Picture. Design of Programming Languages

Functional Programming. Pure Functional Languages

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

LECTURE 16. Functional Programming

CSC 533: Programming Languages. Spring 2015

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

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

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

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

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

Notes on Higher Order Programming in Scheme. by Alexander Stepanov

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

61A LECTURE 22 TAIL CALLS, ITERATORS. Steven Tang and Eric Tzeng July 30, 2013

Functional Programming. Pure Functional Languages

COP4020 Programming Assignment 1 - Spring 2011

CPS 506 Comparative Programming Languages. Programming Language Paradigm

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

CSCC24 Functional Programming Scheme Part 2

Chapter 1. Fundamentals of Higher Order Programming

An Introduction to Scheme

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

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

Functional Programming

Lexical vs. Dynamic Scope

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

Chapter 15. Functional Programming Languages

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Documentation for LISP in BASIC

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

CS 314 Principles of Programming Languages

CSCI337 Organisation of Programming Languages LISP

Organization of Programming Languages CS3200/5200N. Lecture 11

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

CS 314 Principles of Programming Languages. Lecture 16

Lisp Basic Example Test Questions

CS61A Midterm 2 Review (v1.1)

Putting the fun in functional programming

John McCarthy IBM 704

CS 314 Principles of Programming Languages

Functional programming with Common Lisp

Announcement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.

Imperative, OO and Functional Languages A C program is

Lisp. Versions of LISP

Problems 3-1, 3.3, 3.4 and 3.5 in Chapter 3 of Winston and Horn's LISP (see Below)

Functional Languages. Hwansoo Han

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

Symbolic Computation and Common Lisp

Administrivia. Simple data types

Functional Programming Lecture 1: Introduction

The design recipe. Readings: HtDP, sections 1-5. (ordering of topics is different in lectures, different examples will be used)

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

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

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

Review Analyzing Evaluator. CS61A Lecture 25. What gets returned by mc-eval? (not analyzing eval) REVIEW What is a procedure?

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

Introduction to Functional Programming in Haskell 1 / 56

Structure and Interpretation of Computer Programs

CS450 - Structure of Higher Level Languages

Imperative languages

Programming Languages

A Brief Introduction to Scheme (I)

Scheme Quick Reference

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

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

A Brief Introduction to Scheme (II)

Common Lisp. Blake McBride

Homework 1. Notes. What To Turn In. Unix Accounts. Reading. Handout 3 CSCI 334: Spring, 2017

MetacircularScheme! (a variant of lisp)

Functional Programming - 2. Higher Order Functions

CSE413 Midterm. Question Max Points Total 100

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

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

Introduction to Scheme

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

CS 61A Discussion 8: Scheme. March 23, 2017

61A LECTURE 18 SCHEME. Steven Tang and Eric Tzeng July 24, 2013

Introductory Scheme. Revision 1

6.037 Lecture 7B. Scheme Variants Normal Order Lazy Evaluation Streams

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

Transcription:

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, compose them, specialize them, apply them to arguments, etc. We ll look at how func(onal programming things are done in Lisp

eval Remember: Lisp code is just an s- expression You can call Lisp s evalua(on process with the eval func(on > (define s (list 'cadr ' ' (one two three))) > s (cadr ' (one two three)) > (eval s) two > (eval (list 'cdr (car '((quote (a. b)) c)))) b

apply apply takes a func(on and a list of arguments for it and returns the result of applying the func(on to them > (apply + ' (1 2 3)) 6 apply can be given any number of arguments, so long as the last is a list: > (apply + 1 2 ' (3 4 5)) 15 A simple version of apply could be writen as (define (apply f list) (eval (cons f list)))

lambda The define special form creates a func(on and gives it a name However, func(ons need not have names, and we don t need to use define to create them The primi(ve way to create func(ons is to use the lambda special form These are owen called lambda expressions, e.g. (lambda (x) (+ x 1))

lambda expression A lambda expression is a list of the symbol lambda, followed by a list of parameters, fol- lowed by a body of one or more expressions: > (define f (lambda (x) (+ x 2))) > f #<proceedure:f> > (f 100) 102 > ( (lambda (x) (+ x 2)) 100) 102

Lambda expression lambda is a special form When evaluated, it creates a func(on and returns a reference to it The func(on does not have a name A lambda expression can be the first ele- ment of a func(on call: > ( (lambda (x) (+ x 100)) 1) 101 Other languages like python and javascript have adopted the idea

define vs. define (define (add2 x) (+ x 2) ) (define add2 (lambda (x) (+ x 2))) (define add2 #f) (set! add2 (lambda (x) (+ x 2))) The define special form comes in two varieties The three expressions to the left are entirely equivalent The first define form is just more familiar and convenient when defining a function

Func%ons as objects While many PLs allow func(ons as arguments, nameless lambda func(ons add flexibility > (sort '((a 100)(b 10)(c 50)) (lambda (x y) (< (second x) (second y)))) ((b 10) (c 50) (a 100)) There is no need to give the comparator func(on a name

lambdas in other languages Lambda expressions are found in many modern languages, e.g., Python: >>> f = lambda x,y: x*x + y >>> f <func(on <lambda> at 0x10048a230> >>> f(2, 3) 7 >>> (lambda x,y: x*x+y)(2,3) 7

Mapping func%ons Lisp and Scheme have several mapping func(ons map (mapcar in Lisp) is the most useful It takes a func(on and 1 lists and returns a list of the results of applying the func(on to elements taken from each list > (map abs '(3-4 2-5 - 6)) (3 4 2 5 6) > (map + (1 2 3) (4 5 6)) (5 7 9) > (map + (1 2 3) (4 5 6) (7 8 9)) (12 15 18)

More map examples > (map cons '(a b c) '(1 2 3)) ((a. 1) (b. 2) (c. 3)) > (map (lambda (x) (+ x 10)) (1 2 3)) (11 12 13) > (map + '(1 2 3) '(4 5)) map: all lists must have same size; arguments were: #<procedure:+> (1 2 3) (4 5) === context === /ApplicaJons/PLT/collects/scheme/private/misc.ss: 74:7

Defining map Defining a simple one argument version of map is easy (define (map1 func list) (if (null? list) null (cons (func (first list)) (map1 func (rest list)))))

Define Lisp s every and some every and some take a predicate and one or more sequences When given just one sequence, they test whether the elements sa(sfy the predicate > (every odd? (1 3 5)) #t > (some even? (1 2 3)) #t If given >1 sequences, the predicate takes as many args as there are sequences and args are drawn one at a (me from them: > (every > (1 3 5) (0 2 4)) #t

Defining every is easy (define (every1 f list) ;; note the use of the and func(on (if (null? list) #t (and (f (first list)) (every1 f (rest list)))))

Define some similarly (define (some1 f list) (if (null? list) #f (or (f (first list)) (some1 f (rest list)))))

Will this work? You can prove that P is true for some list ele- ment by showing that it isn t false for every one Will this work? > (define (some1 f list) (not (every1 (lambda (x) (not (f x))) list))) > (some1 odd? '(2 4 6 7 8)) #t > (some1 (lambda (x) (> x 10)) '(4 8 10 12)) #t

filter (filter <f> <list>) returns a list of the elements of <list> which sa(sfy the predicate <f> > (filter odd? (0 1 2 3 4 5)) (1 3 5) > (filter (lambda (x) (> x 98.6)) (101.1 98.6 98.1 99.4 102.2)) (101.1 99.4 102.2)

Example: filter (define (filter1 func list) ;; returns a list of elements of list where func is true (cond ((null? list) null) ((func (first list)) (cons (first list) (filter1 func (rest list)))) (#t (filter1 func (rest list))))) > (filter1 even? (1 2 3 4 5 6 7)) (2 4 6)

Example: filter Define integers as a func(on that returns a list of integers between a min and max (define (integers min max) (if (> min max) null (cons min (integers (add1 min) max)))) Define prime? as a predicate that is true of prime numbers and false otherwise > (filter prime? (integers 2 20) ) (2 3 5 7 11 13 17 19)

Here s another pajern We owen want to do something like sum the elements of a sequence (define (sum- list l) (if (null? l) 0 (+ (first l) (sum- list (rest l))))) Other (mes we want their product (define (mul(ply- list l) (if (null? l) 1 (* (first l) (mul(ply- list (rest l)))))

Here s another pajern We owen want to do something like sum the elements of a sequence (define (sum- list l) (if (null? l) 0 (+ (first l) (sum- list (rest l))))) Other (mes we want their product (define (mul(ply- list l) (if (null? l) 1 (* (first l) (mul(ply- list (rest l)))))

Example: reduce Reduce takes (i) a func(on, (ii) a final value and (iii) a list of arguments Reduce of +, 0, (v1 v2 v3 vn) is just V1 + V2 + V3 + Vn + 0 In Scheme/Lisp nota(on: > (reduce + 0 (1 2 3 4 5)) 15 (reduce * 1 (1 2 3 4 5)) 120

Example: reduce (define (reduce func(on final list) (if (null? list) final (func(on (first list) (reduce func(on final (rest list)))))

(define (sum- list list) ;; returns the sum of the list elements (reduce + 0 list)) (define (mul- list list) ;; returns the sum of the list elements (reduce * 1 list)) (define (copy- list list) ;; copies the top level of a list (reduce cons () list)) (define (append- list list) ;; appends all of the sublists in a list (reduce append () list)) Using reduce

The roots of mapreduce MapReduce is a sowware frame- work developed by Google for parallel computa(on on large datasets on computer clusters It s become an important way to exploit parallel compu(ng using conven(onal programming languages and techniques. See Apache s Hadoop for an open source version The framework was inspired by func(onal programming s map, reduce and side- effect free programs

Func%on composi%on Math nota(on: g h is a composi(on of func- (ons g and h If f=g h then f(x)=g(h(x)) Composing func(ons is easy in Scheme > compose #<procedure:compose> > (define (sq x) (* x x)) > (define (dub x) (* x 2)) > (sq (dub 10)) 400 > (dub (sq 10)) 200 > (define sd (compose sq dub)) > (sd 10) 400 > ((compose dub sq) 10) 200

Defining compose Here s compose for two func(ons in Scheme (define (compose2 f g) (lambda (x) (f (g x)))) Note that compose calls lambda which returns a new func(on that applies f to the result of applying g to x We ll look at how the variable environments work to support this in the next topic, closures But first, let s see how to define a general ver- sion of compose taking any number of args

Func%ons with any number of args Defining func(ons that takes any number of arguments is easy in Scheme (define (foo. args) (prinu "My args: ~a\n" args))) If the parameter list ends in a symbol as opposed to null (cf. doted pair), then its value is the list of the remaining arguments values (define (f x y. more- args) ) (define (map f. lists) )

Compose in Scheme (define (compose. FS) ;; Returns the iden(ty func(on if no args given (if (null? FS) (lambda (x) x) (lambda (x) ((first FS) ((apply compose (rest FS)) x))))) ; examples (define (add- a- bang str) (string- append str "!")) (define givebang (compose string- >symbol add- a- bang symbol- >string)) (givebang 'set) ; ===> set! ; anonymous composi(on ((compose sqrt negate square) 5) ; ===> 0+5i

A general every We can easily re- define other func(ons to take more than one argument (define (every fn. args) (cond ((null? args) #f) ((null? (first args)) #t) ((apply fn (map first args)) (apply every fn (map rest args))) (else #f))) (every > (1 2 3) (0 2 3)) => #t (every > (1 2 3) (0 20 3)) => #f

Func%onal Programming Summary Lisp is the archetypal func(onal programming language, in that it treats func(ons as first- class objects and uses the same representa(on for data and code The FP paradigm is a good match for many problems, esp. ones involving reasoning about or op(mizing code or parallel execu(on While no pure FP languages are (yet) considered mainstream, many PLs support a FP style