首页 > 解决方案 > 如何在没有内置函数(如 Enum.count)的情况下在 Elixir 中计算一个数字?

问题描述

如何在没有内置函数(如 Enum.count)的情况下在 Elixir 中计算一个数字。这是我的代码,非常感谢

defmodule Ans do
  @my_favorite_number 0

 def sum([]) do
    0
  end
  def sum([head|tail]) do
    head + sum(tail)

  end

  def average([head|tail]) do
    total = sum([head|tail])
    iterations = Enum.count([head|tail])
    output = total / iterations
  end

  end

标签: countelixir

解决方案


您应该阅读有关尾调用优化的信息。编译器利用这种优化来防止每次递归调用都创建一个新的堆栈帧,这将在您的代码中发生。这是一个如何以sum/1尾递归方式编写函数的示例。主要思想是将返回值保存在accumulator传递给每个调用的变量中,而不是在调用堆栈中建立答案:

def sum(list), do: sum(0, list)
def sum(acc, []), do: acc
def sum(acc, [head | tail]), do: sum(acc + head, tail)

对于count,您可以执行类似的操作,但只需添加1而不是列表项的值:

def count(list), do: count(0, list)
def count(acc, []), do: acc
def count(acc, [_head | tail]), do: count(acc + 1, tail)

推荐阅读