以前に作った span
関数と内包表記を使って 2 から n までの素数。
defmodule MyList do def span(from, to) when from == to, do: [to] def span(from, to), do: [from | span(from + 1, to)] def primes(n) do for x <- span(2, n), is_prime(x), do: x end defp is_prime(2), do: true defp is_prime(3), do: true defp is_prime(n) do m = div(n, 2) Enum.all?(Enum.map(span(2, m), fn x -> rem(n, x) != 0 end)) end end
^o^ > iex practice_10_3.exs Eshell V8.0 (abort with ^G) Interactive Elixir (1.3.4) - press Ctrl+C to exit (type h() ENTER for help) iex(1)> MyList.primes(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]