Erlang - 元素和列表 [英] Erlang - element and list

查看:158
本文介绍了Erlang - 元素和列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是新来的erlang。我想知道如何编写一个返回列表中前N个元素的函数?



我试过:

  take([],_) - > []; 
取([H | T],N)当N> 0 - >取([H,hd(L)| t1(T)],N-1);
取([H | T],N)当N == 0 - > ...(我被困在这里...)

任何提示? thx



更新:我知道有一个名为子列表的功能,但我需要知道如何用自己的方式写这个函数。



我终于找出了答案:

  -module(list)。 
-export([take / 2])。

take(List,N) - >取(列表,N,[])。
take([],_,[]) - > [];
take([],_,List) - >清单;
取([H | T],N,List)当N> 0 - > take(T,N-1,lists:append(List,[H]));
取([H | T],N,List)当N == 0 - >名单。


解决方案

一个简单的解决方案是:

$ b当N> N时,
$ b

  take([H | T],N) 0  - > 
[H | take(T,N-1)];
取(_,0) - > []。

如果列表中没有足够的元素,则会生成错误。



当您使用累加器时,您通常不会将元素附加到其末尾,因为这是非常低效的(每次复制整个列表)。您通常会使用 [H | List] 来推送元素。然后按照相反的顺序进行,但是您可以执行列表:reverse(List)以正确的顺序返回它们。

  take(List,N) - > take(List,N,[])。当N> N时,

取([H | T],N,Acc) 0 - >
take(T,N-1,[H | Acc]);
取(_,0,Acc) - >列表:反向(ACC)。

累加器版本是尾部递归,这是一个好事,但你需要做一个额外的反向,消除一些好处。第一个版本我觉得比较清楚。没有明确的例子。


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.

解决方案

A simple solution is:

take([H|T], N) when N > 0 ->
    [H|take(T, N-1)];
take(_, 0) -> [].

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 a lists:reverse(List) to return them in the right order.

take(List, N) -> take(List, N, []).

take([H|T], N, Acc) when N > 0 ->
    take(T, N-1, [H|Acc]);
take(_, 0, Acc) -> lists:reverse(Acc).

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.

这篇关于Erlang - 元素和列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆