Skip to content

Instantly share code, notes, and snippets.

@josephan
Last active September 29, 2021 20:00
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephan/d2bd28ec691f7754861f8d69d5e818d7 to your computer and use it in GitHub Desktop.
Save josephan/d2bd28ec691f7754861f8d69d5e818d7 to your computer and use it in GitHub Desktop.
Recursive implementation of reduce and reverse in Elixir
defmodule Joseph do
@moduledoc """
This is my module for the challenges from Elixir TV episode 6
"""
@doc """
Reduces a list to a single value from running a function.
Returns an numeric value.
## Examples
iex> Joseph.reduce([1, 2, 3, 4, 5], fn a, b -> a + b end)
15
iex> Joseph.reduce([1, 2, 3, 4, 5], fn a, b -> a * b end)
120
"""
def reduce(list, fun) do
[h|t] = list
do_reduce(t, fun, h)
end
defp do_reduce([], _fun, acc) do
acc
end
defp do_reduce([h|t], fun, acc) do
result = fun.(h, acc)
do_reduce(t, fun, result)
end
@doc """
Reverses the order of a list.
Returns the same list, reversed.
## Examples
iex> Joseph.reverse([1, 2, 3, 4])
[4, 3, 2, 1]
iex> Joseph.reverse([:atom, "string", 42, 3.14])
[3.14, 42, "string", :atom]
"""
def reverse(list) do
do_reverse(list, [])
end
defp do_reverse([], reversed) do
reversed
end
defp do_reverse([h|t], reversed) do
do_reverse(t, [h|reversed])
end
end
@hudsonbay
Copy link

👏👏👏👏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment