-
-
Save lojic/9597160a49e6e9d994e512ef3c2a48d3 to your computer and use it in GitHub Desktop.
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
;; A function to remove all the 2's from a list | |
(define (remove-2 lst) | |
(if (null? lst) | |
lst | |
(let ([ item (car lst) ]) | |
(if (= 2 item) | |
(remove-2 (cdr lst)) | |
(cons item (remove-2 (cdr lst))))))) | |
;; A function to remove all the 7's from a list | |
(define (remove-7 lst) | |
(if (null? lst) | |
lst | |
(let ([ item (car lst) ]) | |
(if (= 7 item) | |
(remove-7 (cdr lst)) | |
(cons item (remove-7 (cdr lst))))))) | |
;; Abstract the argument to allow removing any number | |
(define (remove-n n lst) | |
(if (null? lst) | |
lst | |
(let ([ item (car lst) ]) | |
(if (= n item) | |
(remove-n n (cdr lst)) | |
(cons item (remove-n n (cdr lst))))))) | |
;; Abstract over the comparison to allow removing any object equal to the argument | |
;; such as strings, lists, etc. | |
(define (remove obj is-same? lst) | |
(if (null? lst) | |
lst | |
(let ([ item (car lst) ]) | |
(if (is-same? obj item) | |
(remove obj is-same? (cdr lst)) | |
(cons item (remove obj is-same? (cdr lst))))))) | |
;; Abstract over the comparison to allow comparisons other than equality | |
;; such as is-odd?, contains-only-primes?, is-non-empty-string?, etc. | |
(define (remove pred? lst) | |
(if (null? lst) | |
lst | |
(let ([ item (car lst) ]) | |
(if (pred? item) | |
(remove pred? (cdr lst)) | |
(cons item (remove pred? (cdr lst))))))) | |
;; Recognize and use built-in higher order functions | |
(define (remove pred? lst) | |
(filter (compose not pred?) lst)) | |
;; Allow reusing specific instances | |
(define remove-2 (curry remove is-2?)) | |
(define remove-foo (curry remove (curry string=? "foo"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment