day 1, part 2, simplified tokenize

main
Inga 🏳‍🌈 12 months ago
parent 8963e32886
commit 5f8c81daf2
  1. 36
      day01-hard/main.scm

@ -21,6 +21,8 @@
(define (is-not value) (lambda (x) (not (= x value)))) (define (is-not value) (lambda (x) (not (= x value))))
(define is-not-empty (lambda (x) (not (null? x)))) (define is-not-empty (lambda (x) (not (null? x))))
(define (prepend first-value) (lambda (rest) (cons first-value rest)))
(define Y (lambda (f) (f (lambda (x) ((Y f) x))))) (define Y (lambda (f) (f (lambda (x) ((Y f) x)))))
(define Y2 (lambda (f) (f (lambda (x y) ((Y2 f) x y))))) (define Y2 (lambda (f) (f (lambda (x y) ((Y2 f) x y)))))
@ -60,6 +62,10 @@
'(1 2 3) '(1 2 3)
((first is-not-empty) '(() (1 2 3)))) ((first is-not-empty) '(() (1 2 3))))
(define (coalesce-not-empty default) (lambda (value) ((first is-not-empty) (list value default))))
(define (truthy-chaining f) (lambda (value) (if value (f value) #f)))
(define (compose-two f g) (lambda (x) (f (g x)))) (define (compose-two f g) (lambda (x) (f (g x))))
(define compose (reduce-right compose-two id)) (define compose (reduce-right compose-two id))
@ -73,7 +79,6 @@
(lambda (f) (lambda (n) (lambda (f) (lambda (n)
(if (= n 0) '() (cons value (f (- n 1)))))))) (if (= n 0) '() (cons value (f (- n 1))))))))
;=============== starts-with ====================== ;=============== starts-with ======================
(define starts-with (Y2 (define starts-with (Y2
(lambda (f) (lambda (prefix values) (lambda (f) (lambda (prefix values)
@ -113,23 +118,17 @@
(if (if
(null? values) (null? values)
'(()) '(())
((first is-not-empty) (list ((compose (list
(flat (coalesce-not-empty (f (cdr values)))
((filter id) flat
((map (filter id)
(lambda (token) (map
((lambda (rest) (lambda (token)
(if ((truthy-chaining (compose (list
rest (map (prepend (car token)))
((map (lambda (rest) (f (next rest values))))))
(lambda (rest-tokenized) (starts-with (cdr token) values))))))
(cons (car token) rest-tokenized))) tokens))))))
(f (next rest values)))
#f))
(starts-with (cdr token) values))))
tokens)))
(f (cdr values))
'((77 78) (79 76)))))))))
(define (tokenize tokens) (define (tokenize tokens)
(tokenize-generic tokens (lambda (rest values) rest))) (tokenize-generic tokens (lambda (rest values) rest)))
@ -151,6 +150,7 @@
(define (tokenize-aoc tokens) (define (tokenize-aoc tokens)
(tokenize-generic tokens (lambda (rest values) (cdr values)))) (tokenize-generic tokens (lambda (rest values) (cdr values))))
;=============== solution ====================== ;=============== solution ======================
(define solution-tokens (define solution-tokens
(list (list

Loading…
Cancel
Save