Created
February 26, 2020 02:28
-
-
Save kmicinski/26b360200eb97a8c0b2d5e4adedadf7f 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
#lang racket | |
; takes two lists and builds a list of pairs of each element | |
; return empty list for unused elements as in '(0 1) '(2 3 4) | |
; (zip '(0 1) '(2 3)) --> '((0 . 2) (1 . 3)) | |
(define (zip lst0 lst1) | |
(match (cons lst0 lst1) | |
[(cons `(,hd0 . ,tl0) `(,hd1 . ,tl1)) (cons (cons hd0 hd1) (zip tl0 tl1))] | |
[(cons '() '()) '()] | |
[(cons _ _) '()])) | |
(define zip-test-list '((0 . 4) (1 . 5) (2 . 6))) | |
; takes a list and unzips it, assuming each element is a pair, | |
; return a pair of lists | |
(define (unzip lst) | |
(match lst | |
['() (cons '() '())] | |
[`((,fst-car . ,fst-cdr) . ,tl) | |
; this is a cons cell whose car contains the cars of tl | |
; and whose cdr contains the cdrs of tl | |
(define unzipped-tl (unzip tl)) | |
(cons (cons fst-car (car unzipped-tl)) (cons fst-cdr (cdr unzipped-tl)))])) | |
; map a function over a list | |
(define (map f lst) | |
(define (loop f lst acc) | |
(match lst | |
['() (reverse acc)] | |
[`(,hd . ,tl) (loop f tl (cons (f hd) acc))])) | |
(loop f lst '())) | |
; append two lists | |
; (append '() l) = l | |
; (append (cons e rst) l) = (cons e (append rst l)) | |
(define (append lst0 lst1) | |
(match lst0 | |
['() lst1] | |
[`(,hd . ,tl) (cons hd (append tl lst1))])) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment