Created
August 25, 2014 16:15
-
-
Save grauwoelfchen/898e2369f7b3019022ba to your computer and use it in GitHub Desktop.
Recursion with Scheme
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
;; (maximum '(1 2 5 4)) -> 5 | |
;; (maximum '()) -> ERROR: maximum of empty list! | |
(define maximum | |
(lambda (xs) | |
(cond | |
((null? xs) (error "maximum of empty list!")) | |
((null? (cdr xs)) (car xs)) | |
(else | |
(let ((x (car xs)) (y (maximum (cdr xs)))) | |
(if (> x y) x y)))))) | |
;; (replicate 3 'a) -> (a a a) | |
;; (replicate 0 'b) -> () | |
(define replicate | |
(lambda (n x) | |
(cond | |
((<= n 0) '()) | |
(else (cons x (replicate (- n 1) x)))))) | |
;; (take 3 '(1 1 1 1 1 1)) -> (1 1 1) | |
;; (take 0 '(a b c)) -> () | |
(define take | |
(lambda (n l) | |
(cond | |
((= n 0) '()) | |
((null? l) '()) | |
(else (cons (car l) (take (- n 1) (cdr l))))))) | |
;; (reverse '(1 2 3 4 5)) -> (5 4 3 2 1) | |
;; (reverse '()) -> () | |
(define reverse | |
(lambda (l) | |
(if (null? l) | |
'() | |
(append (reverse (cdr l)) (list (car l)))))) | |
;; infility | |
;; How to use it in scheme ? | |
(define repeat | |
(lambda (n) | |
(cons n (repeat n)))) | |
;; (zip '(1 2 3) '(4 5 6)) -> ((1 4) (2 5) (3 6)) | |
;; (zip '(a b c) '(d)) -> ((a d)) | |
(define zip | |
(lambda (x y) | |
(cond | |
((null? x) '()) | |
((null? y) '()) | |
(else | |
(cons (cons (car x) (list (car y))) | |
(zip (cdr x) (cdr y))))))) | |
;; (elem 2 '(1 2 3 4 5)) -> #t | |
;; (elem 1 '(3 4 5)) -> #f | |
;; (elem 3 '()) -> #f | |
(define elem | |
(lambda (x l) | |
(cond | |
((null? l) #f) | |
((eq? x (car l)) #t) | |
(else (elem x (cdr l)))))) | |
;; (filter <= 3 '(1 2 3 4 5)) -> (1 2 3) | |
;; (filter > 10 '(5 4 3)) -> () | |
(define filter | |
(lambda (f x l) | |
(if (null? l) | |
'() | |
(let | |
((frst (car l)) (rest (cdr l))) | |
(if (f frst x) | |
(cons frst (filter f x rest)) | |
(filter f x rest)))))) | |
;; (quicksort '(1 29 10 23 35 92 22 11)) -> (1 10 11 22 23 29 35 92) | |
;; (quicksort '()) -> () | |
(define quicksort | |
(lambda (l) | |
(cond | |
((null? l) '()) | |
(else | |
(let | |
((pivt (car l)) (rest (cdr l))) | |
(append (quicksort (filter <= pivt rest)) | |
(list pivt) | |
(quicksort (filter > pivt rest)))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment