CS 245 - Programming Languages

Lab 9

Elixir reduce

According to the Elixir on-line documentation (https://hexdocs.pm/elixir/1.12/Enum.html#reduce/3) "Reduce (sometimes called fold) is a basic building block in functional programming. Almost all of the functions in the Enum module can be implemented on top of reduce. " For instance, Enum.map can be implemented using reduce as:
def my_map(enumerable, fun) do
  enumerable
  |> Enum.reduce([], fn x, acc -> [fun.(x) | acc] end)
  |> Enum.reverse()
end
In this lab you will use Enum reduce to implement other of the functions in the Enum module.

Implement the following functions using Enum.reduce. You will need to write small anonymous functions to pass into reduce. Do not write your own recursive functions. As with the map example above, you may use Enum.reverse to change the order of items (but you will not need to).

  1. Enum.count/2
  2. Enum.sum/2
  3. Enum.max/1
  4. Enum.at/2
  5. Enum.join/2
  6. Enum.min_by (this differs from min in that there is a function passed returns the value to be compared rather than just comparing the values themselves). For instance, here are some examples of the use of Enum.min_by/2
            # find the number with the smallest squared value
            Enum.min_by([2,-3,4], fn (x) -> x*x end)
            # answer is 2
    
            # find the longest word -- by finding the smallest difference between 100 and word length
            Enum.min_by(["was", "am", "great", "then", "therefore"], fn (x) -> 100-String.length(x) end)
            # answer is "therefore"
        
Each of these functions is well documented at https://hexdocs.pm/elixir/1.12/Enum.html

What to hand in

Work no more than 80 minutes. If you did not complete everything, send what you have.

Send email to gtowell@brynmawr.edu with your re-implementations using reduce.