The Elixir help page for Enum.reduce/3 says that almost all of the Enum functions can be implemented on top of Enum.reduce/3. I am trying to implement Enum.all?/1 by writing a new function that uses Enum.reduce/3. It works correctly most of the time but in some cases it returns an empty list.
In one case I have invoked the function passing a 1..7 range and a function testing that a value is less than 7. In another case I passed the 1..7 range and a function testing that a value is less than 8.
In the first case my all?/1 function correctly returns false as all values are not less than 7.
In the second case I am expecting true, all values are less than 8 but instead get back an empty list.
Here is my implementation of the all?/1 function .....
defmodule ListsRec5 do
def all?(enumerable, acc, fun \\fn x -> x end) do
enumerable
|> Enum.reduce([], fn x, acc -> fun.(x) and acc end)
end
end
The first test......
ListsRec5.all?(1..7, true, fn x -> x < 7 end)
false
The second test ....
ListsRec5.all?(1..7, true, fn x -> x < 8 end)
[]
I think the second test should return true, not an empty list.
andingtruewith an empty array, that'll eval to the empty array.false and []short-circuits so you getfalse.