count - 如何在没有内置函数(如 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
解决方案
您应该阅读有关尾调用优化的信息。编译器利用这种优化来防止每次递归调用都创建一个新的堆栈帧,这将在您的代码中发生。这是一个如何以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)
推荐阅读
- sql-server - 为什么聚集索引加速 Select Top
- java - 我需要编写一个方法来返回金牌数量多于铜牌然后是银牌的国家名称
- sql - 根据两列的最大对获取行
- delphi - 为什么当 btn 为 NIL 时我可以访问 btn.Caption?
- macos - 如何在 Nix 环境中使 macOS 框架可用于 clang?
- javascript - 在 keydown/keyup 上切换显示/隐藏密码
- angular - RxJS 6 - Angular 6 - 如果触发了新请求,则正确取消当前的 http 请求
- ruby-on-rails - 您将如何编写 zip 文件生成测试?
- ssis - SSIS 包 - 从多个源文件中获取一列
- android - 设备所有者模式下的 StartLockTask() 仍然允许使用后退按钮进行转义