返回列表的最大值
我正在尝试返回列表的最大值。
我有以下代码
list_max([]) ->
[];
list_max([H|T]) ->
list_max(H, T).
list_max(Temp, []) ->
Temp;
list_max(Temp, [H|T]) when H > Temp ->
Temp = H;
list_max(Temp, T).
,但正在努力与 Erlang 建立联系。
如何将某些内容分配给 temp 并将其替换为最高值?
I am trying to return the max of a list.
I have the following code
list_max([]) ->
[];
list_max([H|T]) ->
list_max(H, T).
list_max(Temp, []) ->
Temp;
list_max(Temp, [H|T]) when H > Temp ->
Temp = H;
list_max(Temp, T).
But am struggling to relate to Erlang.
How do I assign something to temp and replace it to the highest?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
Erlang 是我发现展示比解释更容易的语言之一。
并这样称呼它:
Erlang is one of those languages in which I find it easier to show than to explain.
and call it thus:
抱歉,也许我错过了一些东西。您是否在寻找:
Sorry, maybe I'm missing something. Are you looking for:
简短的回答是你不能。 Erlang 中的变量一旦分配就无法更改。
稍微长一点的答案是,虽然您无法更改特定函数调用中的变量,但您始终可以自递归。 Erlang 中的尾递归得到了优化。
在您提供的示例代码中,list_max 将仅查看列表的前两个元素。第四和第五子句应分别再次调用 list_max,并在第一个参数中使用 Temp 的新值。这是函数式语言中常见的事情。在这种情况下,Temp 被称为累加器(我经常将变量命名为 Acc 来反映这种用途,但当然您可以将其命名为任何您想要的名称)。
让我展示另一个解决方案,可以被视为“介于”Macelo 的答案和 stmi 的答案之间:(
我还放弃了检测空列表的子句,因为我认为它并没有真正给你带来太多 - 尽管它现在会抛出一个如果您使用空列表调用它,则例外。)
The short answer is that you can't. Variables in Erlang cannot be changed once assigned.
The slightly longer answer is that, while you can't change a variable inside a particular function call, you can always self-recurse. Tail-recursion in Erlang is optimized.
In the example code that you provided, list_max will only ever look at the first two elements of the list. The fourth and fifth clauses should each call list_max again, with the new value of Temp in the first parameter. This is a common thing to do in functional languages. In this case, Temp is known as an Accumulator (I often name the variable Acc to reflect this use, but of course you can name it whatever you want).
Let me show another solution that could be seen as "in between" Macelo's answer and stmi's answer:
(I also ditched the clause that detects the empty list, because I don't think it really buys you much - though it will now throw an exception if you call it with an empty list.)
Erlang 是一个单一的赋值,所以你不能改变“变量”。您只能创建新的。
我的建议是查看列表模块。在lists.erl中,您会发现:
您不更新Max变量(示例中的Temp),而是使用新值调用函数或从函数返回它。
简单易行...:-)
Erlang is a single assignment so you cannot change "variables". You can only create new ones.
My recommendation is to look at the lists module. Inside lists.erl you will find:
You don't update the Max variable (Temp in your example), but rather call the function with the new value or return it from the function.
Easy peasy... :-)
您还可以在内置函数中表达 not:
You can also express than in built in functions: