Download presentation

Presentation is loading. Please wait.

Published byKory Martin Modified over 2 years ago

1
Higher Order Functions “I hope you’re convinced, by now, that programming languages with first-class functions let you find more opportunities for abstraction, which means your code is smaller, tighter, more reusable, and more scalable.” —Joel Spolsky

2
Eval eval is the heart of REPL Takes an expression, evaluates it and returns it >(eval '(+ 2 5)) 7 >(eval (list '* 2 5 7)) 70 >(eval (eval '''eval)) EVAL

3
Function (#') function returns the object associated with a function name >(function +) # >(defun f (x) (* x x)) F >(function f) (LAMBDA-BLOCK F (X) (* X X)) >(function (lambda (x) (* x x))) (LAMBDA-CLOSURE () () () (X) (* X X)) Exact results depend on implementation (these are GCL) In most contexts, can be abbreviated with #'

4
Apply Takes a function and a list of arguments for it, and returns the result of applying the function to the arguments Last argument must be a list whose final cdr is nil >(apply #'+ '(2 5 6)) 13 >(apply #'* 2 4 '(3 1)) 24

5
Funcall Same as apply, but the arguments don’t need to be in a list >(funcall #'+ 2 3 5 6) 16 >(funcall #'cons 'a 'b) (A. B)

6
Higher Order Functions A Higher Order Function is one that has at least one function as an argument apply and funcall are higher order functions There are many others You can also make your own

7
Mapcar mapcar is a very useful higher order function Applies a function to each element of a list, one at a time, and returns the list of results (mapcar function list) >(mapcar #'evenp '(1 2 3 4 5 6 7)) (NIL T NIL T NIL T NIL) >(mapcar #'oddp '(1 2 3 4 5 6 7)) (T NIL T NIL T NIL T)

8
Define Mapcar (defun my-mapcar (f xs) "Function similar to mapcar" (if (consp xs) (cons (funcall f (car xs)) (my-mapcar f (cdr xs))) nil)) Actual definition is slightly more complicated

9
Anonymous Functions Lambda abstractions are useful in conjunction with higher order functions Example: the following function subtracts n from each element in a list: >(defun subtract-n (n xs) (mapcar #'(lambda (x) (- x n)) xs)) SUBTRACT-N >(subtract-n 5 '(10 9 8 2 1)) (5 4 3 -3 -4)

Similar presentations

OK

Dr. Philip Cannata 1 Programming Languages Chapter 14 – Functional Programming – Lisp.

Dr. Philip Cannata 1 Programming Languages Chapter 14 – Functional Programming – Lisp.

© 2018 SlidePlayer.com Inc.

All rights reserved.

Ads by Google

Download ppt on biodegradable and nonbiodegradable waste Ppt on chromosomes and genes middle school Ppt on role of ngo in india Ppt on sound navigation and ranging system one Ppt on study designs in epidemiology Ppt on european union Ppt on anorexia nervosa Ppt on chapter 3 atoms and molecules lesson Ppt on arc welding process Ppt on listening comprehension