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

Similar documents
Functional Programming. Pure Functional Languages

Introduction to ACL2. CS 680 Formal Methods for Computer Verification. Jeremy Johnson Drexel University

Functional Programming. Pure Functional Languages

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

CSCC24 Functional Programming Scheme Part 2

Organization of Programming Languages CS3200/5200N. Lecture 11

Functional Programming. Big Picture. Design of Programming Languages

COP4020 Programming Languages. Functional Programming Prof. Robert van Engelen

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

Lambda Calculus. CS 550 Programming Languages Jeremy Johnson

CS 314 Principles of Programming Languages

User-defined Functions. Conditional Expressions in Scheme

Functional Programming - 2. Higher Order Functions

An introduction to Scheme

Functional Languages. Hwansoo Han

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

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

Functional Programming Lecture 1: Introduction

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

CS 314 Principles of Programming Languages. Lecture 16

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

Functional Programming. Pure Functional Programming

Box-and-arrow Diagrams

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

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

Chapter 15. Functional Programming Languages

LECTURE 16. Functional Programming

CSC324 Functional Programming Efficiency Issues, Parameter Lists

A Brief Introduction to Scheme (I)

Documentation for LISP in BASIC

YOUR NAME PLEASE: *** SOLUTIONS ***

CPS 506 Comparative Programming Languages. Programming Language Paradigm

CS 314 Principles of Programming Languages

Functional Programming

Programming Languages

Principles of Programming Languages 2017W, Functional Programming

Programming Languages

Introduction to Scheme

FP Foundations, Scheme

Chapter 15. Functional Programming Languages

An Explicit-Continuation Metacircular Evaluator

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

Introduction to Functional Programming in Haskell 1 / 56

CS 342 Lecture 7 Syntax Abstraction By: Hridesh Rajan

Chapter 1. Fundamentals of Higher Order Programming

CSE 341 Section Handout #6 Cheat Sheet

Symbolic Computation

Scheme in Scheme: The Metacircular Evaluator Eval and Apply

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

Functional abstraction

A Brief Introduction to Scheme (II)

Module 8: Local and functional abstraction

COP4020 Programming Assignment 1 - Spring 2011

CS 314 Principles of Programming Languages

CS61A Midterm 2 Review (v1.1)

Extensible Pattern Matching

Scheme: Expressions & Procedures

CSCE 314 TAMU Fall CSCE 314: Programming Languages Dr. Flemming Andersen. Haskell Functions

Imperative languages

An Introduction to Scheme

Module 10: Imperative Programming, Modularization, and The Future

Functional Programming Languages (FPL)

The Typed Racket Guide

Functional Programming in Scheme

Typed Racket: Racket with Static Types

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

Chapter 15 Functional Programming Languages

Scheme Quick Reference

Quick announcement. Midterm date is Wednesday Oct 24, 11-12pm.

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

Chapter 11 :: Functional Languages

Topic III. LISP : functions, recursion, and lists References: Chapter 3 of Concepts in programming languages by J. C. Mitchell. CUP, 2003.

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

6.001: Structure and Interpretation of Computer Programs

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

Scheme Quick Reference

Scheme: Strings Scheme: I/O

Introduction to Functional Programming

SCHEME AND CALCULATOR 5b

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

Streams and Evalutation Strategies

Functional programming with Common Lisp

Shell CSCE 314 TAMU. Haskell Functions

Using Symbols in Expressions (1) evaluate sub-expressions... Number. ( ) machine code to add

Principles of Programming Languages

CS 314 Principles of Programming Languages

CS 360 Programming Languages Interpreters

Syntactic Sugar: Using the Metacircular Evaluator to Implement the Language You Want

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

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

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

Imperative, OO and Functional Languages A C program is

Recursive Functions of Symbolic Expressions and Their Computation by Machine Part I

Functional Programming

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

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

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

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

A Small Interpreted Language

Higher Order Functions in Haskell

Transcription:

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 function application. Programs may also produce functions by returning functions as values. In pure functional programming, this is it, there are no variables, side effects, nor loops. This simplifies semantics but does not reduce computational power. We will investigate the style of programming this implies and how to model the semantics of such programs. 2

Outline 1. Syntax and semantics 2. Functional programming 1. Programs are functions for every input there is a unique output (referential transparency) 2. No variables no assignment and no loops 3. Use recursion for iteration 4. Functions are first class objects 1. Pass as arguments and return as values 3. Racket language and Dr. Racket IDE 3

A Pure Functional Language x 1 = y 1,,x n =y n f(x 1,,x n ) = f(y 1,,y n ) No side-effects, no assignments, no state, no loops Use recursion instead of iteration Still Turing complete Makes reasoning about programs easier 4

C++ Function with Side-Effects #include <iostream> using namespace std; % g++ count.c int cc() { static int x = 0; return ++x; } %./a.out cc() = 1 cc() = 2 cc() = 3 int main() { cout << "cc() = " << cc() << endl; cout << "cc() = " << cc() << endl; } cout << "cc() = " << cc() << endl; 5

Syntax Programs and data are lists delimited by ( and ) or [ and ] and separated by space S expressions (E 1 E n ) Special forms Self evaluating: numbers, Booleans, strings, (quote expr) (if test-expr then-expr else-expr) (cond ([P1 E1] [Pt Et])) (lambda (p1 pn) E1 Et) (define name E) (let ([b1 v1] [bt vt] E) 6

Semantics To evaluate (E1 E2... En), recursively evaluate E1, E2,...,En - E1 should evaluate to a function - and then apply the function value of E1 to the arguments given by the values of E2,...,En. In the base case, there are self evaluating expressions (e.g. numbers and symbols). In addition, various special forms such as quote and if must be handled separately. 7

Read-Eval-Print-Loop (REPL) Dr. Racket IDE (racket-lang.org) Definition Window Click Run to load and run definitions Interaction Window Enter expressions at the prompt (REPL) 8

Example Evaluation > 2 => 2 > (/ 4 6) => 2 3 > + => #<procedure:+> > (+ 2 (* 3 4)) => (+ 2 12) => 14 > (max 1 2 3) => 3 > (1 2 3) => error > (list 1 2 3) => (1 2 3) > (list 1 (2 3) 4) => error > (list 1 (list 2 3) 4) => (1 (2 3) 4)

Booleans and Predicates Boolean constants: #t and #f > (= 2 3) => #f > (or (= 2 3) (not (= 2 3))) => #t > (and #t #t #t) => #t Predicates are Boolean functions Convention is name? > (equal? 2 3) => #f > (eq? 2 3) => #f > (number? 2) => #t > (boolean? (and #t #f)) => #t

Conditional (if test-expr then-expr else-expr) Evaluate test-expr if not #f evaluate and return then-expr else evaluate and return else-expr > (if (< 2 3) 0 1) => 0 > (if (< 3 2) 0 1) => 1 > (if (= 3 (+ 2 1)) 0 1) => 0 > (if (or (= 2 3) (= 3 3)) (+2 3) (+ 3 3)) => 5

Conditional (cond [test-expr1 then-body1] [test-exprn then-bodyn] [else then-body]) Evaluate test-expr1 if #f then goto next case otherwise return then-body1. The else case always returns then-body > (cond [(= 2 3) 2] [(= 3 4) 3] [else 4]) => 4

List Processing Functions > (null? ()) => #t > (null? (1 2 3)) => #f > (car (1 2 3)) => 1 ;same as (first (1 2 3)) > (cdr (1 2 3)) => (2 3) ;same as (rest (1 2 3)) > (cons 1 ()) => (1) > (cons 1 (2 3)) => (1 2 3) > (cons 1 (cons 2 (cons 3 '()))) => (1 2 3) > (cons (cons 1 ()) (2 3)) => ((1) 2 3)

Lambda Expressions (lambda (parameters) body) Evaluates to a function When applied the actual arguments are substituted for the formal parameters into the body which is then evaluated and returned > (lambda (x) (* x x)) => #<procedure> > ((lambda (x) (* x x)) 2) => 4 > (define sqr (lambda (x) (* x x))) > (define (sqr x) (* x x)) ;shorthand for above > (sqr 2) => 4

Recursion In a functional language there are no side effects, hence no assignment and no loops. All control must be done through recursion > (define (fact n) (if (= n 0) 1 (* n (fact (- n 1))))) > (fact 3) => 6 > (define (ones n) (if (= n 0) '() (cons 1 (ones (- n 1))))) > (ones 3) => (1 1 1)

Trace Recursion > (define (fact n) (if (= n 0) 1 (* n (fact (- n 1))))) (fact 0) = 1 (fact 3) = (* 3 (fact 2)) = (* 3 (* 2 (fact 1))) = (* 3 (* 2 (* 1 (fact 0)))) = (* 3 (* 2 (* 1 1))) = 6 When n=0 [base case] no recursion When n>0 [recursive case] recursion occurs

Recursion > (define (fact n) (if (= n 0) 1 (* n (fact (- n 1))))) Similar to mathematical definition define what to compute 1 wwwwwww nn = 0 nn! = nn nn 1! wwwwwww nn > 0 Declarative programming states what to compute rather than how to compute it

Tail Recursion A tail recursive function is a function where the recursive call is the last operation. Such procedures can easily be converted to loops. > (define (fact n) (if (= n 0) 1 (* n (fact (- n 1))))) > (define (factt n sofar) > (if (= n 0) sofar (factt (- n 1) (* n sofar))))) (fact n) = (factt n 1)

Tail Recursion An equivalent loop can be constructed, which updates the arguments each iteration of the loop. for (;;){ if (n == 0) return sofar; else { t1 = n - 1; t2 = sofar * n; n = t1; sofar = t2; } }

Testing Test cases give examples of what a function should compute if implemented properly. They can be used for debugging. (fact 3) = 6 (fact 2) = 2 (fact 1) = 1 (fact 0) = 1

Unit Testing in Racket (require rackunit) (require rackunit/text-ui) (define-test-suite fact-suite (check-equal? (fact 0) 1) (check-equal? (fact 1) 1) (check-equal? (fact 2) 2) (check-equal? (fact 3) 6) ) (run-tests fact-suite 'verbose) 4 success(es) 0 failure(s) 0 error(s) 4 test(s) run 0

Higher Order Functions sort: > (sort '(4 3 2 1) <) => (1 2 3 4) > (sort '("one" "two" "three" "four") string<?) => '("four" "one" "three" "two") map: > (map sqr '(1 2 3 4)) => (1 4 9 16) 22

filter: Higher Order Functions > (filter odd? '(1 2 3 4 5)) => (1 3 5) > (filter even? (1 2 3 4 5)) => (2 4) fold: > (foldr cons '() '(1 2 3 4)) => (1 2 3 4) > (foldr list '() '(1 2 3 4)) => '(1 (2 (3 (4 ())))) > (foldr + 0 '(1 2 3 4)) => 10 > (foldl cons () (1 2 3 4)) => (4 3 2 1) > (foldl list '() '(1 2 3 4)) => '(4 (3 (2 (1 ())))) > (foldl * 1 (1 2 3 4)) => 24 23

Functions that Return Functions Make-adder > (define (make-adder x) (lambda (y) (+ x y))) > (define add1 (make-adder 1)) > (add1 3) => 4 > (define (make-multiplier x) (lambda (y) (* x y))) > (define double (make-multiplier 2)) > (double 3) => 6 24

Function Composition > (define (compose f g) (lambda (x) (f (g x)))) > (define add2 (compose add1 add1)) > (add2 3) => 5 > (define getsecond (compose first rest)) > (getsecond (1 2 3 4 5)) => 2 25

Currying > (define (curry f a) (lambda (b) (f a b))) > (define add1 (curry + 1)) > (add1 3) => 4 > (define double (curry * 2)) > (doulble 3) => 6 26