Skip to content

Instantly share code, notes, and snippets.

@vu3rdd
Created September 2, 2012 17:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vu3rdd/3602105 to your computer and use it in GitHub Desktop.
Save vu3rdd/3602105 to your computer and use it in GitHub Desktop.
map, filter, flatten in racket
#lang racket
(require rackunit)
;; map :: (a -> b -> c) -> [a] -> [b] -> [c]
(define (map f . xs)
(match xs
[(list (list) ...) (list)]
[(list (list x xs ...) ...) (cons (apply f x) (apply map f xs))]))
(check-equal? (map sqr '(1 2 3)) '(1 4 9))
(check-equal? (map + '(1 2 3) '(1 2 3) '(1 2 3)) '(3 6 9))
(check-equal? (map (lambda (x) x) '()) '())
;; flatten :: [[a]] -> [a]
(define (flatten xss)
(match xss
[(list) (list)]
[(? (compose not list?)) (list xss)]
[(list x xs ...) (append (flatten x) (flatten xs))]))
;; implementation without using pattern matching.
(define (flatten1 l)
(cond
[(empty? l) '()]
[(not (list? l)) (list l)]
[else (append (flatten1 (first l)) (flatten1 (rest l)))]))
(check-equal? (flatten '()) '())
(check-equal? (flatten '(1 2 3)) '(1 2 3))
(check-equal? (flatten '(1 (2 3) (((4 5 6) (7))))) '(1 2 3 4 5 6 7))
;; filter :: (a -> Bool) -> [a] -> [a]
(define (filter f xs)
(match xs
[(list) (list)]
[(list x xs ...) (if (f x)
(cons x (filter f xs))
(filter f xs))]))
(check-equal? (filter odd? '(1 2 3 4 5)) '(1 3 5))
(check-equal? (filter even? '(2 4 6 8 10)) '(2 4 6 8 10))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment