Created
September 2, 2012 17:41
-
-
Save vu3rdd/3602105 to your computer and use it in GitHub Desktop.
map, filter, flatten in racket
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
#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