;; Copyright (C) 2017 Dominic Walden
;; This program is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; This program is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with this program. If not, see .
(define fibonacci-stream
(lambda (n1 n2)
(cons-stream (+ n1
n2)
(fibonacci-stream n2
(+ n1
n2)))))
(define even-stream
(lambda (stream)
(if (even? (stream-car stream))
(cons-stream (stream-car stream)
(even-stream (stream-cdr stream)))
(even-stream (stream-cdr stream)))))
(define even-fibonacci-stream
(even-stream (fibonacci-stream 1 1)))
(define max-integer-stream
(lambda (stream max)
(if (> (stream-car stream)
max)
'()
(cons-stream (stream-car stream)
(max-integer-stream (stream-cdr stream)
max)))))
(define stream-sum
(lambda (stream)
(if (null? stream)
0
(+ (stream-car stream)
(stream-sum (stream-cdr stream))))))
(stream-sum (max-integer-stream even-fibonacci-stream
4000000))
(define every-nth-element-of-stream
(lambda (stream n)
(define dispatch
(lambda (stream n i)
(if (= i
1)
(cons-stream (stream-car stream)
(dispatch (stream-cdr stream)
n
n))
(dispatch (stream-cdr stream)
n
(- i 1)))))
(dispatch stream
n
n)))
(define every-3rd-element-fibonacci-stream
(every-nth-element-of-stream (fibonacci-stream 1 2)
3))
(stream-sum (max-integer-stream every-3rd-element-fibonacci-stream
4000000))