Created
June 4, 2024 23:24
-
-
Save achequisde/846083a672e6403560a2ae6ab19e8a53 to your computer and use it in GitHub Desktop.
Custom map implementation written in Scheme.
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
;; my/map | |
;; -- proc: A function | |
;; -- lss: All other arguments. They must be lists | |
;; This is a naive implementation of map, probably | |
;; It does a matrix transposition on lss first | |
;; e.g. given (4 6 7) and (2 1 1), we get ((4 2) (6 1) (7 1)) | |
;; Then we use apply to... apply proc to each sublist | |
;; e.g. given + as proc, and using the list from the previous example, | |
;; we get ((+ 4 2) (+ 6 1) (+ 7 1)) => (6 7 8) | |
(define (my/map proc . lss) | |
(letrec ((transpose (lambda (result1 result2 result3 lss) | |
(cond | |
((null? lss) (transpose (cons (reverse result2) result1) | |
'() | |
'() | |
(reverse result3))) | |
((null? (car lss)) (reverse result1)) | |
(else (transpose result1 | |
(cons (car (car lss)) result2) | |
(cons (cdr (car lss)) result3) | |
(cdr lss))))))) | |
(let loop ((result '()) (ls (transpose '() '() '() lss))) | |
(if (null? ls) | |
(reverse result) | |
(let ((v (apply proc (car ls)))) | |
(loop (cons v result) (cdr ls))))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment