我怎么能写Erlang的列表串连,而无需使用列表模块? [英] How can I write Erlang's list concatenate without using the lists module?

查看:111
本文介绍了我怎么能写Erlang的列表串连,而无需使用列表模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这本书我读关于二郎在它的背面有练习,一个是重新创建列表:附加功能

The book I'm reading about Erlang has exercises in the back of it and one is to re-create the lists:append function.

我能做到这一点简单地使用++运算符,而不是这真的是慢?而且我觉得练习的要点是用我写列表操作做到这一点。

I could do this simply using the ++ operator, but isn't this really slow? And I think the point of the exercise is to do it using list operations that I write.

到目前为止,我能想到的唯一的办法是做这样的事情:

So far the only approach that I could think of is to do something like:

concat([], _, Results)->
  Results;
concat(_, [], Results)->
  Results;
concat([Ah|At],B,Results) ->
  concat(At,B,[Ah|Results]).

但我知道这是不正确...

But I know this is incorrect...

如何去这样做有什么建议?

Any suggestions on how to go about doing this?

编辑:为了澄清这个问题,下面是一个例子输入和输出:

To clarify the question, here is an example input and output:

输入:[[1,2,3],[],[4,5],[6]
输出:[1,2,3,4,5,6]

Input: [[1,2,3],[],[4,5],[6]] Output: [1,2,3,4,5,6]

工作一段时间后,我想出了这个code,以及:

After working a while, I came up with this code as well:

append([A|[B|[T|[]]]]) ->
  append([A++B|T]);
append([H|T]) ->
  H++T.

不过,这仅适用于当列表的大小为3,我怎么能修改此,使其适用于随机大小列出任何给定的量?

However, this only works for when the list is size 3. How can I modify this so that it works for any given amount of randomly sized lists?

推荐答案

您只需要两个参数的concat函数,因为你会被追加到的参数之一,这就是你最终会回来。喜欢的东西(未经测试):

You only need two parameters to your concat function, as you'll be appending to one of the parameters and that's what you'll eventually return. Something like (untested):

concat(L,[]) ->
   L;
concat(L,[H|T]) ->
   concat(L ++ [H],T).

该++是追加操作符,你将不得不这样做是有效的。

The ++ is the append operator, you're going to have to do that to be efficient.

(上面的想法是返回左参数如果我们已经没有更多的左侧,或移动元件中的一个从右侧到左侧后再次调用)。有大概在做反向追加,然后终于扭转了答案更高的效率,但嘿...)

(The idea of the above is to return the left parameter if we've no more left, or call again after moving one of the elements from the right to the left). There's probably more efficiencies around doing the append in reverse and then finally reversing the answer but hey...)

(刚刚看到你的编辑,当然矿山仅适用于两件事情追加,但你可以通过上面的功能,在你的名单列表递归的每个元素...)

(Just saw your edit, and mine of course only works for two things to append, but you can recurse through the above function for each element in your list of lists...)

这篇关于我怎么能写Erlang的列表串连,而无需使用列表模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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