Lazy Sequences
Create a lazy sequence by repeating a value:
Such a sequence is lazy by providing its values on demand, and it is unbounded by providing values forever:
Retrieve the first n elements of a sequence:
Repeat the items of a sequence:
Not the sequence itself, but its items are repeated in a cycle.
Create a sequence based on a starting value and a successor function:
The generated sequence is immutable and stateless:
Many functions on sequences are lazy:
The values are only mapped and filtered as needed.
While many functions on sequences are lazy, some like count and
reduce are eager.
Create a lazy sequence explicitly from another (non-lazy) sequence:
Limit the REPL output size when dealing with infinite sequences:
Realize a lazy sequence, enforcing its computation:
Process the elements of a lazy sequence one by one:
Write a function that produces a lazy sequence:
Exercises
Lazy Fibonacci Numbers
Write a function lazy-fib that returns a lazy sequence of Fibonacci
numbers.
Hint: Use cons and lazy-seq with a recursive function call to
produce the next element. A multi-arity function (with zero and two
arguments) is a good option to provide the initial two Fibonacci
numbers.
Test: (take 10 (fib-stream)) shall return (1 1 2 3 5 8 13 21 34 55), and (nth (fib-stream) 45) shall return 1836311903.
Lazy Prime Numbers
Write a function lazy-primes that returns a lazy sequence of prime
numbers. Write a predicate function is-prime that checks whether or
not the given argument is a prime number.
Hint: Use cons and lazy-seq again. Use the functions take-while
and some to create and process the candidates for the divisibility
test in the is-prime predicate.
Test: (take 10 (lazy-primes)) shall return (2 3 5 7 11 13 17 19 23 29).
Process File Line by Line
Write a function sum-up-to that reads lines from a text file, tries
to parse them as numbers, sums those numbers up until a given limit is
reached, writes the processed numeric lines into a output text file,
and returns the sum. Both source and target paths and the limit
are given as parameters.
Hint: Use with-open, clojure.java.io/reader,
clojure.java.io/writer, and line-seq for (lazy) file line by line
processing. If the lines are exhausted before the limit is reached,
the current sum should be returned.
Test: Given the following file lines.txt:
(sum-up-to lines.txt result.txt 16) shall return 15 and produce a
file result.txt with the following content: