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.

61 lines
1.3 KiB

10 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 (reduce-right reducer initial list)
10 months ago
(if
(null? list)
initial
(reducer (car list) (reduce-right reducer initial (cdr list)))))
10 months ago
(define (map mapper list)
(reduce-right
(lambda (current accumulator) (cons (mapper current) accumulator))
'()
list))
10 months ago
(define (combine combiner a b)
10 months ago
(if (null? a) b (if (null? b) a (combiner a b))))
10 months ago
(define (sum numbers) (reduce-right + 0 numbers))
10 months ago
10 months ago
(define
(repeat value number)
(if
(= number 0)
'()
(cons value (repeat value (- number 1)))))
10 months ago
(define (is-numeric-char char) (if (char-numeric? char) #t #f))
10 months ago
(define (first-last predicate list)
(reduce-right
10 months ago
(lambda (current accumulator)
(combine
(lambda (left right) (cons (car left) (cdr right)))
10 months ago
current
accumulator))
'()
(map
(lambda (entry)
(if (predicate entry) (repeat entry 2) '()))
list)))
10 months ago
10 months ago
(define (solve-line line)
10 months ago
((lambda (first-last-result)
(string->number (list->string first-last-result)))
(first-last is-numeric-char (string->list line))))
10 months ago
(define (solve-all lines)
(sum (map solve-line lines)))
10 months ago
(display (solve-all (read-lines)))