如何在不使用列表模块的情况下编写 Erlang 的列表连接? [英] How can I write Erlang's list concatenate without using the lists module?

查看:29
本文介绍了如何在不使用列表模块的情况下编写 Erlang 的列表连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读的关于 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]

工作一段时间后,我也想出了这个代码:

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.

(上面的想法是如果我们没有更多的左边就返回左边的参数,或者在将一个元素从右边移动到左边后再次调用).反向执行 append 然后最终反转答案可能会提高效率,但是嘿...)

(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天全站免登陆