Presentation is loading. Please wait.

Presentation is loading. Please wait.

Higher Order Functions “I hope you’re convinced, by now, that programming languages with first-class functions let you find more opportunities for abstraction,

Similar presentations


Presentation on theme: "Higher Order Functions “I hope you’re convinced, by now, that programming languages with first-class functions let you find more opportunities for abstraction,"— Presentation transcript:

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)


Download ppt "Higher Order Functions “I hope you’re convinced, by now, that programming languages with first-class functions let you find more opportunities for abstraction,"

Similar presentations


Ads by Google