Powered by AppSignal & Oban Pro
Would you like to see your link here? Contact us

For Comprehension

for-comprehension.livemd

For Comprehension

import IEx.Helpers

Basic

h for/1

Generators

for x <- 1..100, do: x * 2
for x <- 1..100 do
  x * 2
end
for x <- ~c"abcdefg" do
  inspect(x)
end
for x <- %{one: 1, two: 2, three: 3} do
  inspect(x)
end
for x <- [one: 1, two: 2, three: 3] do
  inspect(x)
end
for x <- MapSet.new [one: 1, two: 2, three: 3] do
  inspect(x)
end
for << x <- "abc" >> do
  inspect(x)
end
for x <- 1..3, y <- 1..3, z <- 1..2, do: {x, y, z}
for x <- 1..3, y <- 1..3, z <- 1..2, y == 3, x in [2, 3], do: {x, y, z}

For into

i 1..30//3

Into

for c <- ?a..?z, into: <<>> do
  <>
end
i <<>>
for c <- ?a..?z, into: %{} do
  {<>, 0}
end

# i %{}
for c <- ?a..?z, into: MapSet.new([]) do
  {<>, 0}
end
for c <- ?a..?z, into: [] do
  {String.to_atom(<>), 0} 
  # ":#{c}" |> to_charlist()
end
# |> i

uniq

string = "the quick brown fox jumps over the lazy dog"
string
|> String.graphemes()
|> Enum.filter(&amp;(&amp;1 != " "))
|> Enum.uniq()
for ch <- String.graphemes(string), ch != " ", uniq: true do
  ch
end
# |> length()

reduce

string
|> String.graphemes()
|> Enum.filter(&amp;(&amp;1 != " "))
|> Enum.reduce(%{}, fn ch, counts -> 
  Map.update(counts, ch, 1, fn count -> count + 1 end)
end)
 string
|> String.graphemes()
|> Enum.filter(&amp;(&amp;1 != " "))
|> Enum.reduce(%{}, fn ch, counts -> 
  Map.update(counts, ch, 1, &amp;(&amp;1 + 1))
end)

reduce:

for ch <- String.graphemes(string),
  ch != " ", 
  reduce: %{} do
  count -> Map.update(count, ch, 1, &amp;(&amp;1 + 1)) 
end