HiveBrain v1.2.0
Get Started
← Back to all entries
patternMinor

Is there a better way to write these two nested loops in Erlang?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
erlangtheseloopswaywritebetternestedtwothere

Problem

Since one month, I'm learning Erlang and I like it so much.
Today, I wrote an algorithm to solve a problem.
Some time ago, I used two nested for loops in C# to solve it but, solving the same problem in Erlang, I asked myself if there is a better way to write something similar to the two nested for loops I used before.

Let's say that the two nested for loops in C# are:

for(int i = 100; i<=999;i++)
    {
        for(int j = 100;j<=999;j++)
        {
            int prod = i*j;
              //some logic here..
        }
    }


and the respective code in Erlang is the following:

loopINumber(_,LowerLim,UpperLim,Product) when LowerLim > UpperLim -> {Product};

loopINumber(ILimit,LowerLim,UpperLim,Product) ->
    Product = loopJNumber(ILimit,UpperLim,LowerLim,Product),
    loopINumber(ILimit,LowerLim+1,UpperLim,Product).

loopJNumber(LowerLim,UpperLim,_,Product) when LowerLim > UpperLim -> Product;

loopJNumber(LowerLim,UpperLim,ILimit,Product) ->
    Product = ILimit * LowerLim,
    %% some logic here..
    loopJNumber(LowerLim+1,UpperLim,ILimit,Product).

start(ILimit,JLimit) -> loopINumber(ILimit,ILimit,JLimit,0).


I know that maybe there's something to improve. Being still a beginner in functional languages, most probably I'm still coding in a "sequential" or OOP way. How can I improve this Erlang code?

Solution

In general, nested for loops translate well to list comprehensions:

Prods = [I*J || I <- lists:seq(100,999), J <- lists:seq(100,999)]
// Generates a list of products to perform further logic on

Code Snippets

Prods = [I*J || I <- lists:seq(100,999), J <- lists:seq(100,999)]
// Generates a list of products to perform further logic on

Context

StackExchange Code Review Q#54329, answer score: 3

Revisions (0)

No revisions yet.