Erlang - 元素和列表
我是二郎新手。我想知道如何编写一个返回列表中前 N 个元素的函数?
我试过了:
take([],_) -> [];
take([H|T],N) when N > 0 -> take([H,hd(L)|tl(T)], N-1);
take([H|T],N) when N == 0 -> ... (I'm stuck here...)
有什么提示吗?谢谢
更新:我知道有一个名为“sublist”的函数,但我需要弄清楚如何自己编写该函数。
我终于找到答案了:
-module(list).
-export([take/2]).
take(List,N) -> take(List,N,[]).
take([],_,[]) -> [];
take([],_,List) -> List;
take([H|T], N, List) when N > 0 -> take(T, N-1, lists:append(List,[H]));
take([H|T], N, List) when N == 0 -> List.
I'm new to erlang. I wonder how to write a function which returns the first N elements in a list?
I've tried:
take([],_) -> [];
take([H|T],N) when N > 0 -> take([H,hd(L)|tl(T)], N-1);
take([H|T],N) when N == 0 -> ... (I'm stuck here...)
Any hint? thx
Update: I know there's a function called "sublist" but I need to figure out how to write that function by my own.
I finally figured out the answer:
-module(list).
-export([take/2]).
take(List,N) -> take(List,N,[]).
take([],_,[]) -> [];
take([],_,List) -> List;
take([H|T], N, List) when N > 0 -> take(T, N-1, lists:append(List,[H]));
take([H|T], N, List) when N == 0 -> List.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Erlang 中,
take
拼写为lists:sublist
:In Erlang,
take
is spelledlists:sublist
:一个简单的解决方案是:
如果列表中没有足够的元素,这将生成错误。
当您像现在这样使用累加器时,通常不会将元素附加到其末尾,因为这是非常低效的(每次都会复制整个列表)。通常,您可以使用
[H|List]
将元素推入其中。然后它将按相反的顺序,但您随后执行lists:reverse(List)
以按正确的顺序返回它们。累加器版本是尾递归,这是一件好事,但您需要进行额外的反向操作,这会消除一些好处。我认为第一个版本更清晰。两者都没有明确的案例。
A simple solution is:
This will generate an error if there are not enough elements in the list.
When you use an accumulator as you are doing you do not usually append elements to the end of it as this is very inefficient (you copy the whole list each time). You would normally push elements on to it with
[H|List]
. It will then be in the reverse order but you then do alists:reverse(List)
to return them in the right order.The accumulator version is tail recursive which is a Good Thing but you need to do an extra reverse which removes some of the benefits. The first version I think is clearer. There is no clear case for either.