Functional programming techniques
|
|
- Gregory Hodges
- 6 years ago
- Views:
Transcription
1 Functional programming techniques o Currying o Continuations o Streams. Lazy evaluation Currying o Haskell B. Curry. o Second-order programming: o Functions that return other functions. o Example: A two-arguments function is transformed in a oneargument function that returns a one-argument function. (defun adder (x) #'(lambda (y) (+ x y))) (adder 2) #'(lambda (y) (+ 2 y)) (funcall (adder 2) 3) 5 (setf f (adder 2)) (funcall f 3) 5 ML programming fun adder x y = x + y adder: int int int adder 2: int int
2 Examples (defun member (x l) (when l (or (equal (first l) x) (member x (rest l))))) (defun member-c (x) #'(lambda (list) (labels ((look (l) (when l (or (equal (first l) x) (look (rest l)))))) (look list)))) (defun new-member (a l) (funcall (member-c a) l)) Examples (defun map-c (fn) #'(lambda (args) (labels ((aplica (l) (when l (cons (funcall fn (first l)) (aplica (rest l)))))) (aplica args)))) (defun new-map (fn args) (funcall (map-c fn) args))
3 Currying o Generalization: Transform a function with n = m + k parameters into a function with m parameters that returns a function with k parameters. (defun swapper (x y ls) (cond ((null ls) nil) ((equal (first ls) x) (cons y (swapper x y (rest ls)))) ((equal (first ls) y) (cons x (swapper x y (rest ls)))) (t (cons (first ls) (swapper x y (rest ls)))))) (defun swapper-c (x y) #'(lambda (ls) (labels ((look-up (ls) (cond ((null ls) nil) ((equal (first ls) x) (cons y (look-up (rest ls)))) ((equal (first ls) y) (cons x (look-up (rest ls)))) (t (cons (first ls) (look-up (rest ls))))))) (look-up ls)))) (defun swapper-nou (x y ls) (funcall (swapper-c x y) ls)) (setf pp (swapper-c a b)) (funcall pp (c a d b e)) (c b d a e)
4 Currying o Useful when one (o more) of the arguments of a function remains constant o Efficiency in recursive programming: the stack of functional calls is shorter o Lambda functions of only one argument without losing of representation power o Related to the partial evaluation theorem by Kleene (1952): o Given a computable function f of n variables f(x 1,x 2,...,x n ) and k (k<=n) values a 1,..., a k. It is possible to compute a new function f such that: f (x k+1, x k+2,..., x n ) = f(x 1,x 2,...,x n ) Currying o AI interest: to model partial functions, needed for the management of incomplete reasoning o Partial deduction (logic programming) o Specialization: (A B) C A (B C) o Knowledge-base specialization (Milord II): (A, α), (A B C, ρ) (B C, f ( α, ρ)) a b z... KB... α β ζ b z... KB'... α β ζ z... KB''... α β ζ
5 Continuations o Idea: Given a n-argument function, we add a new continuation argument. The result of the original function is given to the continuation. o (defun f (x) x) o (defun f(x,continuation) (funcall continuation x)) o Program transformation technique based on secondorder functions. New programs are more efficiently represented. o Scheme o SML/NJ, Haskell o Actors model o Multiprocessing, search o Objects containing the state of the computation Example I (no recursive) Without continuations (defun length2 (x) (list x (length x))) (defun print-length2 (list) (format t The length is: ~A (length2 list))) With continuations (defun length2-c (x -c-) (funcall -c- (list x (length x)))) (defun print-length2 (list) (length2-c list # (lambda (val) (format t The length is: ~A (length2 val)))))
6 Continuations (recursive functions) o Program transformation technique based on secondorder functions. New programs are more efficiently represented. o Idea: Given a one-argument function, we find a new two-argument tail-recursive function. The first argument is of the same type that the original one and, the second is a function called continuation. o It is easy to define a new tail-recursive function. o Problem: second-order function representation is expensive. o Benefits when continuations can be represented as simple data structures, for instance, lists. Continuations (recursive functions) o Suppose the following function: f(x) = if p then q else E where x can appear in p, q and E o f appears only one time in E, applied over a sub expression of x, f(s(x)) o In the non trivial case a, where p[a/x] is false, the computation returns r = f(s(a)), γ = λw.ew where Ew = E[f(s(x))/w] o The function γ is applied over r, γ(r)
7 Continuations o Equivalent function for f: f(x) = f-tr(x,id) f-tr(x,γ) = γ(f(x)) = if p then γ(q) else f-tr(s(x),λw.γew) [Field i Harrison, 1988] o The function γ is called a continuation, the pending computation to perform after the calculation of the recursive call. Example II (recursive) o Optimization of tail-recursive calls No tail-recursive (defun fact (n) (if (= n 0) 1 (* n (fact (- n 1))))) (defun fact-c (n -c-) (if (= n 0) (funcall -c- 1) (fact-c (- n 1) # (lambda (val) (funcall -c- (* n val)))))) (defun fact (n) (fact-c n # (lambda (val) val)))
8 Memoize (defun memo (fn &key (key #'first) (test #'eql) name) "Return a memo-function of fn." (let ((table (make-hash-table :test test))) (setf (get name :memo) table) #'(lambda (&rest args) (let ((k (funcall key args))) (multiple-value-bind (val found-p) (gethash k table) (if found-p val (setf (gethash k table) (apply fn args)))))))) (defun clear-memoize (fn-name) "Clear the hash table from a memo function." (let ((table (get fn-name :memo))) (when table (clrhash table)))) (defun memoize (fn-name &key (key #'first) (test #'eql)) "Replace fn-name's global definition with a memoized version." (clear-memoize fn-name) (setf (symbol-function fn-name) (memo (symbol-function fn-name) :name fn-name :key key :test test))) Example III o Continuation in a local function Σ n x (defun sum-iter (n) (let ((sum 0)) (loop (if (= n 0) (return sum)) (setq sum (+ sum n)) (setq n (- n 1))))) (defun sum-clean (n) (labels ((sum-loop (n sum) (if (= n 0) sum (sum-loop (- n 1) (+ sum n))))) (sum-loop n 0))) (defun sum-cont (n -c-) (labels ((sum-loop (n sum) (if (= n 0) (funcall -c- sum) (sum-loop (- n 1) (+ sum n))))) (sum-loop n 0)))
9 Coroutines (make-array '(4 2 3) :initial-contents '(((a b c) (1 2 3)) ((d e f) (3 1 2)) ((g h i) (2 3 1)) ((j k l) (0 0 0)))) array-dimension aref (defun write-matrix (M) (let ((heigth (array-dimension M 0)) (width (array-dimension M 1))) (labels ((write-loop (i j corou) (cond ((= i heigth) nil) ((= j width) (write-loop (1+ i) 0 corou)) (t (funcall corou #'(lambda (item corou) (setf (aref M i j) item) (write-loop i (1+ j) corou))))))) (write-loop 0 0 corou))))) (defun read-matrix (M) (let ((heigth (array-dimension M 0)) (width (array-dimension M 1))) (labels ((read-loop (i j corou) (cond ((= i heigth) nil) ((= j width) (read-loop (1+ i) 0 corou)) (t (funcall corou (aref M i j) (read-loop i (1+ j) corou))))))) (read-loop 0 0 corou))))) (defun transfer-matrix (M1 M2) (let ((reader (read-matrix M1)) (writer (write-matrix M2))) (funcall writer reader))) Coroutines M1 = #2A((1 2 3)(4 5 6)) M2 = #2A((nil nil)(nil nil)) (funcall (write-matrix M2)(read-matrix M1)) M2 = #2A((1 2)(3 4)) (funcall (labels ((write-loop (i j corou) (cond ((= i 2) nil) ((= j 2) (write-loop (1+ i) 0 corou)) (t (funcall corou #'(lambda (item corou) (setf (aref M2 i j) item) (write-loop i (1+ j) corou))))))) (write-loop 0 0 corou))) (labels ((read-loop (i j corou) (cond ((= i 2) nil) ((= j 3) (read-loop (1+ i) 0 corou)) (t (funcall corou (aref M1 i j) (read-loop i (1+ j) corou))))))) (read-loop 0 0 corou)))) (funcall (labels ((read-loop (i j corou) (cond ((= i 2) nil) ((= j 3) (read-loop (1+ i) 0 corou)) (t (funcall corou (aref M1 i j) (read-loop i (1+ j) corou))))))) (read-loop 0 0 corou))) #'(lambda (item corou) (setf (aref M2 0 0) item) (write-loop 0 1 corou))) (funcall #'(lambda (item corou) (setf (aref M2 0 0) item) (write-loop 0 1 corou)) (aref M1 0 0) (read-loop 0 1 corou))) (setf (aref M2 0 0) (aref M1 0 0)) (write-loop 0 1 (read-loop 0 1 corou))))
10 Control Flow o Continuations are useful to define control strategies o Common Lisp uses continuations in: o BLOCK/RETURN_FROM lexical o CATCH/THROW dynamic (catch tag (...) (...)...) (if (...) (block then (setq...) (list... (return-from then...))) (...) (defun f (x) (catch 'hola (+ x 1) (+ 5 (g x)))) (throw tag (...)) (defun g (x) (if (< x 5) 567 (throw 'hola 10000))) Control Flow OnLisp: Chapter 20 o These mechanisms can be described with the function CALL-WITH-CURRENT-CONTINUATION (no Common Lisp) o Scheme (lisp dialect) o (+ 1 call/cc (lambda (cont) ( ))) 321 o (+ 1 call/cc (lambda (cont) (+ 20 (cont 300)))) 301 (defmacro block (name &rest forms) `(call-with-current-continuation #'(lambda (,name),@forms))) (defmacro return-from (name &optional value) `(funcall,name,value))
11 ATN (Augmented transition network) s::= np vp to-be np pred np::= proper-noun pronoun det noun vp::= to-be np to-be pred pred::= adj pp pp::= prep np adj::= nice small blue prep::= to in on out to-be ::= is are was were det::= the proper-noun::= maria carles antoni noun::= house car table pronoun::= mine yours ours theirs Maria is nice The house is blue The table is mine Two continuations: success or failure ATN (Augmented transition network) I (defun cont-atn (s) (parse-s s (cond ((null s) success) (T (funcall return)))) 'failure))) (defun parse-s (s success failure) (parse-np s (parse-vp s success return)) (categoria? 'to-be s (parse-np s (parse-pred s sucess return)) return)) failure)))) Success Failure (defun parse-np (s success failure) (categoria? 'proper-noun s sucess (categoria? 'pronoun s sucess (categoria? 'det s (categoria? 'noun s sucess return)) failure)))))) Syntax? (cont-atn (Maria is nice)) (parse-s (Maria is nice) success1 failure1) (parse-np (Maria is nice success2 failure2) (categoria? proper-noun (Maria is nice) success2 failure3)
12 ATN II (defun parse-pred (s success failure) (categoria? 'adj s success (parse-pp s success failure)))) (defun parse-pp (s success failure) (categoria? 'prep s (parse-np s success return)) failure)) (defun categoria? (caract s success failure) (if (or (null s) (not (categoriap (first s) caract))) (funcall failure) (funcall success (rest s) failure))) (defun categoriap (mot tipus) (case tipus (adj (member mot '(nice small blue))) (prep (member mot '(to in on out))) (to-be (member mot '(is are was were))) (det (member mot '(the))) (proper-noun (member mot '(maria carles antoni))) (noun (member mot '(house car table))) (pronoun (member mot '(mine yours ours theirs))))) (categoria? proper-noun (Maria is nice) success2 failure3) (funcall success2 (is nice) failure3) (funcall # (lambda(s return) (parse-vp s success1 return)) (is nice) failure3) (parse-vp (is nice) success1 failure3) (categoria? to-be (is nice) success1 failure3) (funcall # (lambda(s return) (parse-np s success1 return)) (nice) failure3) ATN III (defun parse-np (s success failure) (categoria? 'proper-noun s success (categoria? 'pronoun s success (categoria? 'det s (categoria? 'noun s success return)) failure)))))) (defun parse-vp (s success failure) (categoria? 'to-be s (parse-np s success return)) (categoria? 'to-be s (parse-pred s success return)) failure))))
13 ATN IV (categoria? proper-noun (The house is mine) success2 failure3) (funcall failure3) (funcall (categoria? 'pronoun (The house is mine) success2 (categoria? 'det s ) (funcall (categoria? 'det (The house is mine) (categoria? 'noun s success2 return)) failure2))))))) (categoria? to-be (is mine) success1 failure3) IA interests o Pros o Search and backtracking can be simplified. o Interesting control mechanisms. Necessary to define languages. o Modular and compact programming of ATNs o No backtracking o Continuation over failure states. o Cons o Read and write this kind of code is not easy. o Problematic program debugging with anonymous functions o Inspiration
CS 842 Ben Cassell University of Waterloo
CS 842 Ben Cassell University of Waterloo Recursive Descent Re-Cap Top-down parser. Works down parse tree using the formal grammar. Built from mutually recursive procedures. Typically these procedures
More informationINF4820. Common Lisp: Closures and Macros
INF4820 Common Lisp: Closures and Macros Erik Velldal University of Oslo Oct. 19, 2010 Erik Velldal INF4820 1 / 22 Topics for Today More Common Lisp A quick reminder: Scope, binding and shadowing Closures
More informationScheme. 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
More informationCommon LISP Tutorial 1 (Basic)
Common LISP Tutorial 1 (Basic) CLISP Download https://sourceforge.net/projects/clisp/ IPPL Course Materials (UST sir only) Download https://silp.iiita.ac.in/wordpress/?page_id=494 Introduction Lisp (1958)
More informationFunctional programming with Common Lisp
Functional programming with Common Lisp Dr. C. Constantinides Department of Computer Science and Software Engineering Concordia University Montreal, Canada August 11, 2016 1 / 81 Expressions and functions
More informationCommon LISP-Introduction
Common LISP-Introduction 1. The primary data structure in LISP is called the s-expression (symbolic expression). There are two basic types of s-expressions: atoms and lists. 2. The LISP language is normally
More informationLisp Basic Example Test Questions
2009 November 30 Lisp Basic Example Test Questions 1. Assume the following forms have been typed into the interpreter and evaluated in the given sequence. ( defun a ( y ) ( reverse y ) ) ( setq a (1 2
More informationAnnouncement. Overview. LISP: A Quick Overview. Outline of Writing and Running Lisp.
Overview Announcement Announcement Lisp Basics CMUCL to be available on sun.cs. You may use GNU Common List (GCL http://www.gnu.org/software/gcl/ which is available on most Linux platforms. There is also
More informationStreams, 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
More informationINF4820: Algorithms for Artificial Intelligence and Natural Language Processing. More Common Lisp
INF4820: Algorithms for Artificial Intelligence and Natural Language Processing More Common Lisp Stephan Oepen & Murhaf Fares Language Technology Group (LTG) September 6, 2017 Agenda 2 Previously Common
More informationFunctional Languages. CSE 307 Principles of Programming Languages Stony Brook University
Functional Languages CSE 307 Principles of Programming Languages Stony Brook University http://www.cs.stonybrook.edu/~cse307 1 Historical Origins 2 The imperative and functional models grew out of work
More informationCommon 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
More informationA Brief Introduction to Common Lisp
A Brief Introduction to Common Lisp David Gu Schloer Consulting Group david_guru@gty.org.in A Brief History Originally specified in 1958, Lisp is the second-oldest highlevel programming language in widespread
More informationImperative languages
Imperative languages Von Neumann model: store with addressable locations machine code: effect achieved by changing contents of store locations instructions executed in sequence, flow of control altered
More informationModern Programming Languages. Lecture LISP Programming Language An Introduction
Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation
More informationCIS4/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
More informationSymbolic Computation and Common Lisp
Symbolic Computation and Common Lisp Dr. Neil T. Dantam CSCI-56, Colorado School of Mines Fall 28 Dantam (Mines CSCI-56) Lisp Fall 28 / 92 Why? Symbolic Computing: Much of this course deals with processing
More informationAlgorithms for AI and NLP (INF4820 Lisp & FSAs)
S NP Det N VP V The dog barked LTOP h 1 INDEX e 2 def q rel bark v rel prpstn m rel LBL h 4 dog n rel LBL h RELS LBL h 1 ARG0 x 5 LBL h 9 8 ARG0 e MARG h 3 RSTR h 6 ARG0 x 2 5 ARG1 x BODY h 5 7 HCONS h
More informationRobot 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
More informationFunctional 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).
More informationControl in Sequential Languages
CS 242 2012 Control in Sequential Languages Reading: Chapter 8, Sections 8.1 8.3 (only) Section 7.3 of The Haskell 98 Report, Exception Handling in the I/O Monad, http://www.haskell.org/onlinelibrary/io-13.html
More informationPutting the fun in functional programming
CM20167 Topic 4: Map, Lambda, Filter Guy McCusker 1W2.1 Outline 1 Introduction to higher-order functions 2 Map 3 Lambda 4 Filter Guy McCusker (1W2.1 CM20167 Topic 4 2 / 42 Putting the fun in functional
More informationFunctional 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
More informationLambda 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
More informationUMBC CMSC 331 Final Exam
UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy
More informationLambda Calculus see notes on Lambda Calculus
Lambda Calculus see notes on Lambda Calculus Shakil M. Khan adapted from Gunnar Gotshalks recap so far: Lisp data structures basic Lisp programming bound/free variables, scope of variables Lisp symbols,
More informationFUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY,
FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 4. LISP: PROMĚNNÉ, DALŠÍ VLASTNOSTI FUNKCÍ, BLOKY, MAPOVACÍ FUNKCIONÁLY, ITERAČNÍ CYKLY, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší
More informationCSCI337 Organisation of Programming Languages LISP
Organisation of Programming Languages LISP Getting Started Starting Common Lisp $ clisp i i i i i i i ooooo o ooooooo ooooo ooooo I I I I I I I 8 8 8 8 8 o 8 8 I \ `+' / I 8 8 8 8 8 8 \ `-+-' / 8 8 8 ooooo
More informationAllegro 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
More informationA little bit of Lisp
B.Y. Choueiry 1 Instructor s notes #3 A little bit of Lisp Introduction to Artificial Intelligence CSCE 476-876, Fall 2017 www.cse.unl.edu/~choueiry/f17-476-876 Read LWH: Chapters 1, 2, 3, and 4. Every
More informationLecture 09: Data Abstraction ++ Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree.
Lecture 09: Data Abstraction ++ Parsing Parsing is the process of translating a sequence of characters (a string) into an abstract syntax tree. program text Parser AST Processor Compilers (and some interpreters)
More informationCOP4020 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
More informationIntroduction 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,
More informationA Genetic Algorithm Implementation
A Genetic Algorithm Implementation Roy M. Turner (rturner@maine.edu) Spring 2017 Contents 1 Introduction 3 2 Header information 3 3 Class definitions 3 3.1 Individual..........................................
More informationLisp: Lab Information. Donald F. Ross
Lisp: Lab Information Donald F. Ross General Model program source text stream What you need to write lexical analysis lexemes tokens syntax analysis is_id, is_number etc. + grammar rules + symbol table
More informationComputer 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
More informationStreams 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
More informationStreams and Lazy Evaluation in Lisp
Streams and Lazy Evaluation in Lisp Overview Different models of expression evaluation Lazy vs. eager evaluation Normal vs. applicative order evaluation Computing with streams in Lisp Motivation Unix Pipes
More informationFunctions, Conditionals & Predicates
Functions, Conditionals & Predicates York University Department of Computer Science and Engineering 1 Overview Functions as lambda terms Defining functions Variables (bound vs. free, local vs. global)
More informationA 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,
More informationScheme 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,
More information4/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
More informationFP Foundations, Scheme
FP Foundations, Scheme In Text: Chapter 15 1 Functional Programming -- Prelude We have been discussing imperative languages C/C++, Java, Fortran, Pascal etc. are imperative languages Imperative languages
More informationSummer 2017 Discussion 10: July 25, Introduction. 2 Primitives and Define
CS 6A Scheme Summer 207 Discussion 0: July 25, 207 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,
More informationRecursion & Iteration
Recursion & Iteration York University Department of Computer Science and Engineering 1 Overview Recursion Examples Iteration Examples Iteration vs. Recursion Example [ref.: Chap 5,6 Wilensky] 2 Recursion
More informationUMBC CMSC 331 Final Exam
UMBC CMSC 331 Final Exam Name: UMBC Username: You have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for answers that are needlessly wordy
More informationWhy do we need an interpreter? SICP Interpretation part 1. Role of each part of the interpreter. 1. Arithmetic calculator.
.00 SICP Interpretation part Parts of an interpreter Arithmetic calculator Names Conditionals and if Store procedures in the environment Environment as explicit parameter Defining new procedures Why do
More informationSymbolic 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
More informationOrganization 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
More informationFunctional Languages. Hwansoo Han
Functional Languages Hwansoo Han Historical Origins Imperative and functional models Alan Turing, Alonzo Church, Stephen Kleene, Emil Post, etc. ~1930s Different formalizations of the notion of an algorithm
More informationFunctional Programming. Contents
Functional Programming Gunnar Gotshalks 2003 September 27 Contents Introduction... 2 Example for Inner Product... 2 Basis Set for Functionals... 3 Example Function Definitions... 3 Lisp Builtin Functionals...
More informationCMSC 331 Final Exam Section 0201 December 18, 2000
CMSC 331 Final Exam Section 0201 December 18, 2000 Name: Student ID#: You will have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points for
More informationJatha. Common Lisp in Java. Ola Bini JRuby Core Developer ThoughtWorks Studios.
Jatha Common Lisp in Java Ola Bini JRuby Core Developer ThoughtWorks Studios ola.bini@gmail.com http://olabini.com/blog Common Lisp? Common Lisp? ANSI standard Common Lisp? ANSI standard Powerful Common
More informationDocumentation 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
More informationChapter 15. Functional Programming Languages
Chapter 15 Functional Programming Languages Copyright 2009 Addison-Wesley. All rights reserved. 1-2 Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages
More informationINTRODUCTION 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
More informationITERATORS AND STREAMS 9
ITERATORS AND STREAMS 9 COMPUTER SCIENCE 61A November 12, 2015 1 Iterators An iterator is an object that tracks the position in a sequence of values. It can return an element at a time, and it is only
More informationCPS 506 Comparative Programming Languages. Programming Language Paradigm
CPS 506 Comparative Programming Languages Functional Programming Language Paradigm Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming
More informationLISP. Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits.
LISP Everything in a computer is a string of binary digits, ones and zeros, which everyone calls bits. From one perspective, sequences of bits can be interpreted as a code for ordinary decimal digits,
More informationAssociative Database Managment WIlensky Chapter 22
Associative Database Managment WIlensky Chapter 22 DB-1 Associative Database An associative database is a collection of facts retrievable by their contents» Is a poodle a dog? Which people does Alice manage?»
More informationFunctional Programming
Functional Programming COMS W4115 Prof. Stephen A. Edwards Spring 2003 Columbia University Department of Computer Science Original version by Prof. Simon Parsons Functional vs. Imperative Imperative programming
More informationAssociative Database Managment
Associative Database Managment WIlensky Chapter 22 DB-1 Associative Database An associative database is a collection of facts retrievable by their contents» Is a poodle a dog? Which people does Alice manage?»
More informationUser-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
More informationDeferred operations. Continuations Structure and Interpretation of Computer Programs. Tail recursion in action.
Deferred operations Continuations 6.037 - Structure and Interpretation of Computer Programs Mike Phillips (define the-cons (cons 1 #f)) (set-cdr! the-cons the-cons) (define (run-in-circles l) (+
More informationMIDTERM EXAMINATION - CS130 - Spring 2005
MIDTERM EAMINATION - CS130 - Spring 2005 Your full name: Your UCSD ID number: This exam is closed book and closed notes Total number of points in this exam: 231 + 25 extra credit This exam counts for 25%
More informationNotes 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
More informationImperative, OO and Functional Languages A C program is
Imperative, OO and Functional Languages A C program is a web of assignment statements, interconnected by control constructs which describe the time sequence in which they are to be executed. In Java programming,
More informationAnnouncements. Today s Menu
Announcements 1 Today s Menu Finish Introduction to ANNs (original material by Dr. Mike Nechyba) > Slides 58-60 > Adjusting the Learning Rate Loose Ends in > Lambda Expressions Review > I/O Functions >
More informationNormal 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
More informationFall 2018 Discussion 8: October 24, 2018 Solutions. 1 Introduction. 2 Primitives
CS 6A Scheme Fall 208 Discussion 8: October 24, 208 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
More informationFunctional 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
More informationUMBC CMSC 331 Final Exam Section 0101 December 17, 2002
0 / 0 1 / 20 UMBC CMSC 331 Final Exam Section 0101 December 17, 2002 Name: Student ID#: 2 / 25 3 / 20 4 / 25 5 / 20 6 /40 7 /40 You will have two hours to complete this closed book exam. We reserve the
More informationLisp. Versions of LISP
Lisp Versions of LISP Lisp is an old language with many variants Lisp is alive and well today Most modern versions are based on Common Lisp LispWorks is based on Common Lisp Scheme is one of the major
More informationControl in Sequential Languages
Control in Sequential Languages Structured Programming Go to considered harmful Exceptions structured jumps that may return a value dynamic scoping of exception handler Continuations Function representing
More information(defvar *state* nil "The current state: a list of conditions.")
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;; GPS engine for blocks world ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; (defvar *dbg-ids* nil "Identifiers used by dbg") (defvar *state* nil "The current state: a list of conditions.")
More informationHomework. Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25
Homework Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25 Copyright c 2002 2017 UMaine Computer Science Department 1 / 33 1 COS 140: Foundations
More informationChapter 15. Functional Programming Languages
Chapter 15 Functional Programming Languages Chapter 15 Topics Introduction Mathematical Functions Fundamentals of Functional Programming Languages The First Functional Programming Language: Lisp Introduction
More informationLecture #2 Kenneth W. Flynn RPI CS
Outline Programming in Lisp Lecture #2 Kenneth W. Flynn RPI CS Items from last time Recursion, briefly How to run Lisp I/O, Variables and other miscellany Lists Arrays Other data structures Jin Li lij3@rpi.edu
More informationFunctional Programming
Functional Programming CS 1025 Computer Science Fundamentals I Stephen M. Watt University of Western Ontario When the Function is the Thing In O-O programming, you typically know where an action is needed,
More information19 Machine Learning in Lisp
19 Machine Learning in Lisp Chapter Objectives Chapter Contents ID3 algorithm and inducing decision trees from lists of examples. A basic Lisp implementation of ID3 Demonstration on a simple credit assessment
More informationA Quick Introduction to Common Lisp
CSC 244/444 Notes last updated ug. 30, 2016 Quick Introduction to Common Lisp Lisp is a functional language well-suited to symbolic I, based on the λ-calculus and with list structures as a very flexible
More informationFunctional Programming with Common Lisp
Functional Programming with Common Lisp Kamen Tomov ktomov@hotmail.com July 03, 2015 Table of Contents What is This About? Functional Programming Specifics Is Lisp a Functional Language? Lisp Says Hi Functional
More informationINF4820: Algorithms for Artificial Intelligence and Natural Language Processing. Common Lisp Fundamentals
INF4820: Algorithms for Artificial Intelligence and Natural Language Processing Common Lisp Fundamentals Stephan Oepen & Murhaf Fares Language Technology Group (LTG) August 30, 2017 Last Week: What is
More informationFUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE,
FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 2. ÚVOD DO LISPU: ATOMY, SEZNAMY, FUNKCE, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší budoucnosti L I S P - Introduction L I S P
More informationFUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 3. LISP: ZÁKLADNÍ FUNKCE, POUŽÍVÁNÍ REKURZE,
FUNKCIONÁLNÍ A LOGICKÉ PROGRAMOVÁNÍ 3. LISP: ZÁKLADNÍ FUNKCE, POUŽÍVÁNÍ REKURZE, 2011 Jan Janoušek MI-FLP Evropský sociální fond Praha & EU: Investujeme do vaší budoucnosti Comments in Lisp ; comments
More informationLECTURE 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
More informationProgramming Language Pragmatics
Chapter 10 :: Functional Languages Programming Language Pragmatics Michael L. Scott Historical Origins The imperative and functional models grew out of work undertaken Alan Turing, Alonzo Church, Stephen
More informationJohn McCarthy IBM 704
How this course works SI 334: Principles of Programming Languages Lecture 2: Lisp Instructor: an arowy Lots of new languages Not enough class time to cover all features (e.g., Java over the course of 34-36:
More informationProgramming Languages
Programming Languages Lambda Calculus and Scheme CSCI-GA.2110-003 Fall 2011 λ-calculus invented by Alonzo Church in 1932 as a model of computation basis for functional languages (e.g., Lisp, Scheme, ML,
More informationSection 10: LISP to Scheme. Evolution of Software Languages
Section Evolution of Software Languages Theo D'Hondt Bachelor of Computer Science Faculty of Sciences and Bio-Engineering Sciences Vrije Universiteit Brussel Academic Year 2015-2016 Evolution of Software
More informationCS 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
More informationIntroduction 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
More informationReading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25
Homework Reading: Chapter 17 Homework: All exercises from Chapter 17 Due: 10/27 Correction: Chapter 16 homework is due 10/25 Copyright c 2002 2017 UMaine School of Computing and Information S 1 / 33 COS
More informationCMSC 331 Final Exam Section 0201 December 18, 2000
CMSC 331 Final Exam Section 0201 December 18, 2000 Name: nswers Student ID#: You will have two hours to complete this closed book exam. We reserve the right to assign partial credit, and to deduct points
More informationHistory. Functional Programming. Based on Prof. Gotshalks notes on functionals. FP form. Meaningful Units of Work
History Functional Programming Based on Prof. Gotshalks notes on functionals 1977 Turing 1 Lecture John Backus described functional programming The problem with current languages is that they are word-at-a-time
More informationArtificial Intelligence Programming
Artificial Intelligence Programming Rob St. Amant Department of Computer Science North Carolina State University Lisp basics NC State University 2 / 99 Why Lisp? Some recent Lisp success stories include
More informationCS131 Typed Lambda Calculus Worksheet Due Thursday, April 19th
CS131 Typed Lambda Calculus Worksheet Due Thursday, April 19th Name: CAS ID (e.g., abc01234@pomona.edu): I encourage you to collaborate. collaborations below. Please record your Each question is worth
More informationDepartment of Computer and information Science Norwegian University of Science and Technology
Department of Computer and information Science Norwegian University of Science and Technology http://www.idi.ntnu.no/ A Crash Course in LISP MNFIT272 2002 Anders Kofod-Petersen anderpe@idi.ntnu.no Introduction
More informationObject Oriented Programming (OOP)
Object Oriented Programming (OOP) o New programming paradigm o Actions Objects o Objects Actions o Object-oriented = Objects + Classes + Inheritance Imperative programming o OOP (Object-Oriented Programming)
More informationCS A331 Programming Language Concepts
CS A331 Programming Language Concepts Lecture 10 Alternative Programming Languages (Functional LISP Declarative - PROLOG) March 24, 2014 Sam Siewert Functional PL Concepts Based on Lambda Calculus Output
More information