Solutions of some puzzles in Scheme (Lisp), my first experience with it.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

66 lines
1.3 KiB

12 months ago
#!/usr/bin/guile -s
!#
(use-modules (ice-9 rdelim))
(define (read-lines)
(let loop ((line (read-line)))
(if
(eof-object? line)
'()
(cons line (loop (read-line))))))
(define (map list mapper)
(if
(null? list)
'()
(cons (mapper (car list)) (map (cdr list) mapper))))
12 months ago
(define (reduce list reducer current)
(if
(null? list)
current
(reduce (cdr list) reducer (reducer current (car list)))))
12 months ago
(define (combine a b combiner)
12 months ago
(if
12 months ago
(null? a)
b
12 months ago
(if
12 months ago
(null? b)
a
(combiner a b))))
12 months ago
(define (sum numbers) (reduce numbers + 0))
12 months ago
(define
(repeat value number)
(if
(= number 0)
'()
(cons value (repeat value (- number 1)))))
12 months ago
(define (is-numeric-char char) (if (char-numeric? char) #t #f))
12 months ago
(define (first-last list predicate)
12 months ago
(reduce
(map list (lambda (entry)
(if (predicate entry) (repeat entry 2) '())))
(lambda (current accumulator)
(combine
current
accumulator
(lambda (current rest)
(cons (car current) (cdr rest)))))
'()))
12 months ago
12 months ago
(define (solve-line line)
12 months ago
((lambda (first-last-result)
(string->number (list->string first-last-result)))
12 months ago
(first-last (string->list line) is-numeric-char)))
12 months ago
(define (solve-all lines)
12 months ago
(sum (map lines solve-line)))
12 months ago
(display (solve-all (read-lines)))