Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Elixir Stream by Examples

Elixir Stream by Examples

Presented at ElixirCamp 3 (March 16–19, 2018) in Lord Somers Camp, Somers, VIC

Wu Qing

March 18, 2018
Tweet

More Decks by Wu Qing

Other Decks in Programming

Transcript

  1. Enum Module • Provide functions to work with collections that

    can be enumerated over • Functions in Enum always produce immediate results
  2. Enum examples iex(1)> result1 = 1..10 |> Enum.map(&(&1 + 20))

    [21, 22, 23, 24, 25, 26, 27, 28, 29, 30] iex(2)> result2 = result1 |> Enum.filter(&(rem(&1, 2) == 0)) [22, 24, 26, 28, 30] iex(3)> result2 |> Enum.reduce(0, &+/2) 130
  3. Stream module iex(1)> result1 = 1..10 |> Stream.map(&(&1 + 20))

    #Stream<[enum: 1..10, funs: [#Function<46.51599720/1 in Stream.map/2>]]> iex(2)> result2 = result1 |> Stream.filter(&(rem(&1, 2) == 0)) #Stream<[enum: 1..10, funs: [#Function<46.51599720/1 in Stream.map/2>, #Function<39.51599720/1 in Stream.filter/2>]]> iex(3)> result2 |> Enum.reduce(0, &+/2) 130
  4. Summary • Stream module is very handy for lazy evaluation

    • saves unnecessary iterations and memory • determine when to trigger evaluation