From 7e979bb2cf71466da03b16625afa007fbf19650c Mon Sep 17 00:00:00 2001 From: Inga Date: Mon, 4 Dec 2023 04:25:13 +0000 Subject: [PATCH] reimplemented map using reduce --- day01-easy/main.scm | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/day01-easy/main.scm b/day01-easy/main.scm index b27da6b..a2e49e7 100755 --- a/day01-easy/main.scm +++ b/day01-easy/main.scm @@ -10,22 +10,22 @@ '() (cons line (loop (read-line)))))) -(define (map list mapper) +(define (reduce-right reducer initial list) (if (null? list) - '() - (cons (mapper (car list)) (map (cdr list) mapper)))) + initial + (reducer (car list) (reduce-right reducer initial (cdr list))))) -(define (reduce list reducer current) - (if - (null? list) - current - (reduce (cdr list) reducer (reducer current (car list))))) +(define (map mapper list) + (reduce-right + (lambda (current accumulator) (cons (mapper current) accumulator)) + '() + list)) -(define (combine a b combiner) +(define (combine combiner a b) (if (null? a) b (if (null? b) a (combiner a b)))) -(define (sum numbers) (reduce numbers + 0)) +(define (sum numbers) (reduce-right + 0 numbers)) (define (repeat value number) @@ -36,23 +36,25 @@ (define (is-numeric-char char) (if (char-numeric? char) #t #f)) -(define (first-last list predicate) - (reduce - (map list (lambda (entry) - (if (predicate entry) (repeat entry 2) '()))) +(define (first-last predicate list) + (reduce-right (lambda (current accumulator) (combine + (lambda (left right) (cons (car left) (cdr right))) current - accumulator - (lambda (current rest) (cons (car current) (cdr rest))))) - '())) + accumulator)) + '() + (map + (lambda (entry) + (if (predicate entry) (repeat entry 2) '())) + list))) (define (solve-line line) ((lambda (first-last-result) (string->number (list->string first-last-result))) - (first-last (string->list line) is-numeric-char))) + (first-last is-numeric-char (string->list line)))) (define (solve-all lines) - (sum (map lines solve-line))) + (sum (map solve-line lines))) (display (solve-all (read-lines)))