Skip to content

Instantly share code, notes, and snippets.

@potatosalad
Created July 19, 2024 20:53
Show Gist options
  • Save potatosalad/ec141e0af95aa7ce06a7de51aa9bed4a to your computer and use it in GitHub Desktop.
Save potatosalad/ec141e0af95aa7ce06a7de51aa9bed4a to your computer and use it in GitHub Desktop.
# 1. Comprehensions: add one to each item
xs_input = [1, 2, 3]
xs_output = for x <- xs_input, into: [], do: x + 1
# => [2, 3, 4]
# 1. Map: add one to each item
xs_input = [1, 2, 3]
xs_output = Enum.map(xs_input, & &1 + 1)
# => [2, 3, 4]
# 2. Flat Map: return [x, -(x + 1)] if x is odd, otherwise []
xs_input = [1, 2, 3]
xs_output = Enum.flat_map(xs_input, fn
x when rem(x, 2) === 0 -> []
x -> [x, -(x + 1)]
end)
# => [1, -2, 3, -4]
# 3. Reduce: return the same as #2 above, but also count the even numbers
xs_input = [1, 2, 3]
{xs_output, evens_count} = Enum.reduce(xs_input, {[], 0}, fn
x, {out, evens} when rem(x, 2) === 0 -> {out, evens + 1}
x, {out, evens} -> {out ++ [x, -(x + 1)], evens}
end)
# => {[1, -2, 3, -4], 1}
# 4. Hand-written functions: binary protocols
defmodule MyDecoder do
@event_tag ?e
@message_tag ?m
def decode(input), do: decode(input, [], [])
defp decode(<< @event_tag :: 8, event_id :: 8, rest :: bytes >>, events, messages) do
decode(rest, [event_id | events], messages)
end
defp decode(<< @message_tag :: 8, len :: 8, message :: bytes-size(len), rest :: bytes >>, events, messages) do
decode(rest, events, [message | messages])
end
defp decode(<<>>, events, messages) do
{Enum.reverse(events), Enum.reverse(messages)}
end
end
MyDecoder.decode(<<?m, 2, "ab", ?e, 1, ?e, 2, ?m, 1, "c">>)
# => {[1, 2], ["ab", "c"]}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment