在Erlang中迭代笛卡尔积分,而不首先生成列表 [英] Iterate over a cartesian product in Erlang without generating a list first

查看:75
本文介绍了在Erlang中迭代笛卡尔积分,而不首先生成列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

与下列Python代码相当的Erlang是什么?

What's the Erlang equivalent to the following Python code:

for x in range(9):
    for y in range(9):
        for z in range(9):
            foo(x, y, z)

我知道我可以用 C = [{X,Y,Z} || X <列表:seq(1,9),Y < - 列表:seq(1,9),Z < - 列表:seq(1,9)] then FOO([]) - >完成的; foo([H | T]) - > blah blah。

I know I can generate the product first with C = [{X,Y,Z} || X<- lists:seq(1,9), Y<- lists:seq(1,9), Z<- lists:seq(1,9)] then foo([])->done; foo([H|T])->blah blah.

如果没有辅助列表,只能使用递归

How do I do it without an auxiliary list, using recursion only?

推荐答案

您可以使用三个递归函数来执行。

You could do it with three recursive functions.

可能可以在功能头中使用一些复杂的模式匹配来执行。

You might be able to do it with some complex pattern-matching in function head.

但是,最简单的跳过辅助列表创建的方法是在列表理解中调用您的函数

But easiest way to skip creation of auxiliary list is to call your function inside list comprehension

C = [foo(X, Y, Z) || X<- lists:seq(1,9), 
                     Y<- lists:seq(1,9),  
                     Z<- lists:seq(1,9)]

其中 foo / 3 处理一个元素。

这篇关于在Erlang中迭代笛卡尔积分,而不首先生成列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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