(define sum-of-file (lambda (source-file-name lst) (let ((source (open-input-file source-file-name))) ; Open the file. (let loop ((next (read source))) ; Try to read a number. (if (not (eof-object? next)) ;if not end of file reached: (begin (if (zero? (list-ref lst 0)) ; if list is empty (begin (list-set! lst 0 next) ) ; else (begin (add! lst next) ) ) ) ; else ;(begin ; (display "end of file reached")(newline) ;) ) (if (eof-object? next) ; If you get the end-of-file object, ;if (begin (close-input-port source) ; close the file ) ; end ;else (loop (read source)) ; try to read another number, ) ; and repeat the loop. ) ) ) ) ; list-length calculates the length of the list (define list-length (lambda (l) (let loop ((i 0) (l l)) (if (null? l) i (loop (+ i 1) (cdr l)) ) ) ) ) ; list-set! sets the nth position of a list to object (define list-set! (lambda (ls n obj) (if (zero? n) (set-car! ls obj) (list-set! (cdr ls) (- n 1) obj) ) ) ) (define (add! lst el) (if (null? (cdr lst)) (set-cdr! lst (list el)) (add! (cdr lst) el) ) ) ; for loop macro (define-macro for (lambda (var init test incr . branch) `(let ((,var ,init)) (let v () (if ,test (begin ,@branch ,incr (v)) ) ) ) ) ) ; ++ macro to increment a counter (define-macro ++ (lambda (var) `(begin (set! ,var (+ ,var 1)) ,var ) ) ) ; list-length calculates the length of the list ; swap! swaps 2 elements in a list, given two indexes (define swap! (lambda (lst s1 s2) (let ((temp (list-ref lst s1))) (list-set! lst s1 (list-ref lst s2)) (list-set! lst s2 temp) ) ) ) ; bubblesort walks trough a list and sorts the elements (define bubblesort (lambda (lst) (for j 0 (< j (list-length lst)) (++ j) (for i 0 (< i (- (list-length lst) 1)) (++ i) (if (> (list-ref lst i) (list-ref lst (+ i 1))) (swap! lst i (+ i 1)) ) ) ) ) ) ; define a list (define x (list 0)) (begin (display x)(newline) (sum-of-file "c:\bubble-input.txt" x) (display x)(newline) (bubblesort x) (display x)(newline) )