返回首页 - Notes - 2015

用 Elixir 计算阶乘


写法一

defmodule Test do

  def fact(n), do: fact(n, 1)

  def fact(0, result), do: result

  def fact(n, result), do: fact(n - 1, n * result)

end


for n <- Enum.to_list(0..9) do
  IO.puts "fact(#{n}) = #{Test.fact(n)}"
end

写法二

defmodule Test do

  def fact(n, result \\ 1)

  def fact(0, result), do: result

  def fact(n, result), do: fact(n - 1, n * result)

end


for n <- Enum.to_list(0..9) do
  IO.puts "fact(#{n}) = #{Test.fact(n)}"
end

写法三

defmodule Test do

  def fact(n, result \\ 1) do
    case n do
      0 -> result
      _ -> fact(n - 1, n * result)
    end
  end

end


for n <- Enum.to_list(0..9) do
  IO.puts "fact(#{n}) = #{Test.fact(n)}"
end

写法四

defmodule Test do

  def fact(n, result \\ 1)

  def fact(n, result) do
    case n do
      0 -> result
      _ -> fact(n - 1, n * result)
    end
  end

end


for n <- Enum.to_list(0..9) do
  IO.puts "fact(#{n}) = #{Test.fact(n)}"
end

写法五

fact = &(case &1 do
  0 -> &2
  _ -> &3.(&1 - 1, &1 * &2, &3)
end)


for n <- Enum.to_list(0..9) do
  IO.puts "fact(#{n}) = #{fact.(n, 1, fact)}"
end

date:2015-11-20、2015-11-26、2015-11-27