Skip to content

Instantly share code, notes, and snippets.

@lojic
Created October 15, 2021 16:47
Show Gist options
  • Save lojic/9597160a49e6e9d994e512ef3c2a48d3 to your computer and use it in GitHub Desktop.
Save lojic/9597160a49e6e9d994e512ef3c2a48d3 to your computer and use it in GitHub Desktop.
;; 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