-
-
Save omnibs/c662c677517905f57424 to your computer and use it in GitHub Desktop.
Alternate version of Linq101: Query Reuse
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This is a hacky way of doing the same as this: | |
# https://github.com/omnibs/elixir-linq-examples#linq101-query-reuse | |
numbers = [5, 4, 1, 3, 9, 8, 6, 7, 2, 0] | |
# We use agents to hold mutable state. | |
{:ok, pid} = Agent.start_link(fn -> numbers end) | |
# We turn our agent into a stream to defer linking | |
# the Stream.filter to the value of the array. | |
# Otherwise Agent.update below would have no effect. | |
numbers_stream = Stream.resource( | |
fn -> Agent.get(pid, & &1) end, | |
fn | |
[head | tail] -> {[head], tail} | |
_ -> {:halt, nil} | |
end, | |
fn _ -> end) | |
low_numbers = numbers_stream | |
|> Stream.filter(& &1 <= 3) | |
IO.puts "First run numbers <= 3:" | |
for n <- low_numbers, do: IO.puts n | |
Agent.update(pid, fn x -> x |> Enum.map(& -&1) end) | |
IO.puts "Second run numbers <= 3:" | |
for n <- low_numbers, do: IO.puts n |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment