Last active
September 29, 2021 20:00
-
-
Save josephan/d2bd28ec691f7754861f8d69d5e818d7 to your computer and use it in GitHub Desktop.
Recursive implementation of reduce and reverse in Elixir
This file contains hidden or 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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
ππππ