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
> 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.
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.
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With