All functions in the Enum
module are eager. When performing multiple operations on enumerables with the Enum
module, each operation is going to generate an intermediate result.
The Stream
module is a lazy alternative to the eager Enum
module. It offers many of the same functions as Enum
, but instead of generating intermediate results, it builds a series of computations that are only executed once the stream is passed to a function from the Enum
module.
Streams implement the Enumerable protocol and are composable -- you can chain them together to create more complex functionality.
You are a huge fan of the Numberphile Youtube channel and you just saw a cool video about the Lucas Number Sequence. You want to create this sequence using Elixir.
While designing your function, you want to make use of lazy evaluation, so that you can generate as many numbers as you want, but only if you need to -- So you decide to use a stream.
Add a guard clause to raise an error if a non-integer or an integer less than 1 is used to generate the sequence. Doing this as the first step will prevent infinite recursion bugs in later steps.
LucasNumbers.generate("Hello World")
# => ** (ArgumentError) count must be specified as an integer >= 1
You know that the sequence has two starting numbers which don't follow the same rule. Write two base case clauses to return these numbers:
LucasNumbers.generate(1)
# => [2]
LucasNumbers.generate(2)
# => [2, 1]
For any sequence longer than 2, you know that you need to add the previous two numbers to get the next number and so on. Write the generalized case.
LucasNumbers.generate(3)
# => [2, 1, 3]
LucasNumbers.generate(4)
# => [2, 1, 3, 4]
Sign up to Exercism to learn and master Elixir with 57 concepts, 159 exercises, and real human mentoring, all for free.