Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested loop equivalent

Tags:

haskell

I want to do a list of concatenations in Haskell. I have [1,2,3] and [4,5,6] and i want to produce [14,15,16,24,25,26,34,35,36]. I know I can use zipWith or sth, but how to do equivalent of: foreach in first_array foreach in second_array

I guess I have to use map and half curried functions, but can't really make it alone :S

like image 443
Machiaweliczny Avatar asked Jun 03 '13 19:06

Machiaweliczny


People also ask

What is the alternative for for loop?

> forEach() This method takes a function and executes it for every element. This alternative for “for” loop is only used when we do not have a better higher order function to use in that situation.

What is nested loop in simple words?

A nested loop means a loop statement inside another loop statement. That is why nested loops are also called “loop inside loops“. We can define any number of loops inside another loop.

Is nested for loop and nested loop same?

A nested loop is a loop inside the body of the outer loop. The inner or outer loop can be any type, such as a while loop or for loop. For example, the outer for loop can contain a while loop and vice versa.


2 Answers

You could use list comprehension to do it:

[x * 10 + y | x <- [1..3], y <- [4..6]]

In fact this is a direct translation of a nested loop, since the first one is the outer / slower index, and the second one is the faster / inner index.

like image 170
zw324 Avatar answered Oct 21 '22 02:10

zw324


You can exploit the fact that lists are monads and use the do notation:

do
  a <- [1, 2, 3]
  b <- [4, 5, 6]
  return $ a * 10 + b

You can also exploit the fact that lists are applicative functors (assuming you have Control.Applicative imported):

(+) <$> (*10) <$> [1,2,3] <*> [4,5,6]

Both result in the following:

[14,15,16,24,25,26,34,35,36]
like image 16
Nikita Volkov Avatar answered Oct 21 '22 01:10

Nikita Volkov