elixir

Elixir function does not return expected result


This is my code which should sum all numbers between 0 and "number" if it is either multiply of 3 or 5, but always return 0

defmodule Challenge do
  def solution(number) do 
    result = 0
    for i <- 0..number-1 do
      if rem(i, 5) == 0 || rem(i, 3) == 0 do
        result = result + i
      end
    end
    result
  end
end

This is test:

defmodule TestSolution do
  use ExUnit.Case
  import Challenge, only: [solution: 1]

  def test_solution(n, expected) do
    assert solution(n) == expected
  end
  
  test "basic tests" do
    test_solution 10, 23
  end
end

Solution

  • In Elixir, variables are immutable, so you can't really change result variable as in your example, it stays within for do code block. Your example would work fine in a OOPS language but Elixir being functional you need to change approach a bit. Elixir provides an Enum module to iterate through a list in much more effective way and your solution can easily be replaced with Enum module.

     defmodule Challenge do
      def solution(number) do 
        0..number-1
        |> Enum.filter(fn x -> rem(x, 5) == 0 || rem(x, 3) == 0 end)
        |> Enum.sum()
      end
    end