过度使用Erlang的警卫? [英] Overuse of guards in Erlang?
问题描述
我有以下函数,该函数需要一个像5的数字,并创建一个从1到该数字的所有数字的列表,因此请创建(5)。返回[1,2,3,4,5]。
I have the following function that takes a number like 5 and creates a list of all the numbers from 1 to that number so create(5). returns [1,2,3,4,5].
我认为我使用过的守卫过度,并且想知道是否有更好的方法可以编写以下内容:
I have over used guards I think and was wondering if there is a better way to write the following:
create(N) ->
create(1, N).
create(N,M) when N =:= M ->
[N];
create(N,M) when N < M ->
[N] ++ create(N + 1, M).
推荐答案
create(N,N) -> [N];
create(N,M) -> [N|create(N + 1, M)]. % Don't use ++ to prefix a single element.
这不太一样(您可以提供-5),但是如果您提供有意义的输入。无论如何,我都不会理会额外的检查,因为这两种方法都会很快崩溃。
This isn't quite the same (you could supply -5), but it behaves the same if you supply meaningful inputs. I wouldn't bother with the extra check anyway, since the process will crash very quickly either way.
BTW,您的代码本身存在递归深度问题。可以解决此问题:
BTW, you have a recursion depth problem with the code as-is. This will fix it:
create(N) ->
create(1, N, []).
create(N, N, Acc) -> [N|Acc];
create(N, M, Acc) -> create(N, M - 1, [M|Acc]).
这篇关于过度使用Erlang的警卫?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!