;; The first three lines of this file were inserted by DrRacket. They record metadata
;; about the language level of this file in a form that our tools can easily process.
#reader(lib "htdp-intermediate-lambda-reader.ss" "lang")((modname module-10) (read-case-sensitive #t) (teachpacks ()) (htdp-settings #(#t constructor repeating-decimal #f #t none #f () #f)))
;; a magic trick: recursion with only lambdas.
((lambda (F L) (F F L))
(lambda (self mylist)
(cond [(empty? mylist) 0]
[else
(+ (first mylist)
(self self (rest mylist)))]))
(list 2 3 5 7 11))
(define (sum-to-n n)
(cond [(= n 0) 0]
[else
(+ n (sum-to-n (- n 1)))]))
(sum-to-n 5)
(define (sum-evens-minus-sum-odds L)
(local [
(define odds (filter odd? L))
(define evens (filter even? L))
(define sum-odds (foldr + 0 odds))
(define sum-evens (foldr + 0 evens))
]
(- sum-evens sum-odds)))
(sum-evens-minus-sum-odds (list 2 3 5))
(define (normalize L)
(local [
(define sum-of-L (foldr + 0 L))
(define final-answer
(map (lambda (x) (/ x sum-of-L)) L))
]
final-answer
))
(normalize (list 4 2 14))
(define (sum-odds-or-evens L)
(local [
(define odds (filter odd? L))
(define evens (filter even? L))
]
(cond [(> (length odds)
(length evens))
(foldr + 0 odds)]
[else
(foldr + 0 evens)])))
;; let's make that harder to read....
(define (sum-odds-or-evens2 L)
(local [
(define odds (filter odd? L))
(define evens (filter even? L))
]
(foldr + 0
(cond [(> (length odds)
(length evens))
odds]
[else
evens]))))
(define (keep-multiples n L)
(filter (lambda (x) (= 0 (remainder x n))) L))
(define (even-mean-minus-odd-mean L)
(local [
;; (mean M) return the mean of M.
;; mean: (listof Num -> Num
(define (mean M) (/ (foldr + 0 M) (length M)))
]
(- (mean (filter even? L))
(mean (filter odd? L)))))
(even-mean-minus-odd-mean (list 16 14 5 1))