reimplemented map using reduce

main
Inga 🏳‍🌈 12 months ago
parent b245076e88
commit 7e979bb2cf
  1. 40
      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)))

Loading…
Cancel
Save