I am going through Streams in Dave Thomas’s book and here I am having difficulties in understanding the following program.
For, example what is receive in sleep function and why to use it?
What is after in sleep function?
How this whole program is executed?
Why Dave Thomas suddenly jumped to such a complex program just after explaining the basics of Stream.
defmodule Countdown do
# sleep mode
def sleep(seconds) do
receive do
after
seconds * 1000 -> nil
end
end
def say(text) do
spawn(fn -> :os.cmd('say #{text}') end)
end
def timer do
Stream.resource(
# start of next minute or number of seconds in a minute
fn ->
{_h, _m, s} = :erlang.time()
60 - s - 1
end,
# wait for the next second
fn
0 ->
{:halt, 0}
count ->
sleep(1)
{[inspect(count)], count - 1}
end,
# nothing to deallocate
fn _ -> nil end
)
end
end






















