Skip to content

Instantly share code, notes, and snippets.

@jestinepaul
Created December 6, 2011 04:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jestinepaul/1436740 to your computer and use it in GitHub Desktop.
Save jestinepaul/1436740 to your computer and use it in GitHub Desktop.
Introduction to Functional Programming - Part 3
;; Map
;; ---
(map car '((1 2) (3 4) (5 6) (7 8)))
(map cdr '((1 2) (3 4) (5 6) (7 8)))
(map reverse '((1 2 3 4 5) (6 7 8 9 10) (11 12 13 14 15)))
(map string? '(3.4 5 1/4 "stringy" '("not" "me") "strungy"))
(map append '((a b c) (x y z)) '((d e) (p d q)))
(map + '(10 200 3000) '(7 8 9))
(map cons '("Haley" "Sarah" "Bond [arrogant pause]")
'(("Joel" "Osment") ("Jessica" "Parker") ("James" "Bond")))
(map list '(1 2 3) '(10 20 30) '(100 200 300) '(1000 2000 3000))
(define (unary-map fn seq)
(if (null? seq) '()
(cons (fn (car seq)) (unary-map fn (cdr seq)))))
(unary-map list '(a "b" 4.5 (#f #t #t)))
(unary-map / '(5 6 99 121))
;; Apply
;; -----
(apply + '(1 2 3 4))
(sqrt (apply + (map * '(3 4) '(3 4))))
(define (average num-list)
(/ (apply + num-list) (length num-list)))
(average '(3 5 9 11 3))
(average '(99998 99999 100000 100001 100002))
(average '(3.4 8.3 2.7 6.6))
;; Revisiting the Flatten Problem
;; -------------------------------
(define (flatten-list ls)
(cond ((null? ls) '())
((not (list? ls)) (list ls))
(else (apply append (map flatten-list ls)))))
(flatten-list '(1 2 (3) 4))
(flatten '(this (list (also has) substance) ((((([deep])))))))
;; Inner Function Definitions and Lambdas
;; --------------------------------------
(define (translate numbers delta)
(define (shift number)
(+ number delta))
(map shift numbers))
(define (translate numbers delta)
(map (lambda (number) (+ number delta)) numbers))
;; Power Set
;; ---------
(define (power-set set)
(if (null? set) '(())
(let ((power-set-of-rest (power-set (cdr set))))
(append power-set-of-rest
(map (lambda (subset) (cons (car set) subset))
power-set-of-rest)))))
(power-set '(1 2 3 4))
(power-set '("Nils" "Nolan" "Eric"))
(power-set '(#\a #\e #\i #\o #\u))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment