Lambda, First-Class and Higher-Order Functions
(lambda (x) (* x x)) ; anonymous function
((lambda (x) (* x x)) 5) ; 25
(define square (lambda (x) (* x x))) ; (define (square x) ...) is sugar for this
(map (lambda (x) (* x 2)) '(1 2 3)) ; (2 4 6)
(map + '(1 2 3) '(10 20 30)) ; (11 22 33)
(filter odd? '(1 2 3 4 5)) ; (1 3 5)
(fold-left + 0 '(1 2 3 4)) ; 10 (R6RS/SRFI-1: fold; Racket: foldl)
(apply max '(3 9 2)) ; 9
(for-each (lambda (x) (display x)) '(1 2 3))
;; Functions returning functions
(define (compose f g) (lambda (x) (f (g x))))
(define add1-then-double (compose (lambda (x) (* 2 x)) (lambda (x) (+ x 1))))
(add1-then-double 5) ; 12
(define (curry f x) (lambda (y) (f x y)))
((curry + 10) 5) ; 15
;; Common Lisp (Lisp-2): #' and funcall
(mapcar #'(lambda (x) (* x 2)) '(1 2 3)) ; (2 4 6)
(mapcar #'+ '(1 2 3) '(10 20 30)) ; (11 22 33)
(remove-if-not #'oddp '(1 2 3 4 5)) ; (1 3 5)
(reduce #'+ '(1 2 3 4)) ; 10
(funcall (lambda (x) (* x x)) 5) ; 25
;; Clojure
(map #(* % 2) [1 2 3]) ; (2 4 6): #() reader shorthand
(filter odd? (range 10))
(reduce + [1 2 3 4])
(->> (range 10) (filter even?) (map #(* % %)) (reduce +)) ; 120: threading macro
(comp inc #(* 2 %)) ; composition
(partial + 10) ; partial application