90 likes | 177 Views
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. Eval. eval is the heart of REPL
E N D
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
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
Function (#') • function returns the object associated with a function name >(function +) #<compiled-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 #'
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
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)
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
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)
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
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)