Nested loop equivalent

I want to make 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 make an equivalent: foreach in first_array foreach in second_array

I guess I need to use the functions of the card and half curry, but I can not do it alone: โ€‹โ€‹S

+7
source share
6 answers

For this you can use a list comprehension:

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

This is actually a direct translation of the nested loop, since the first is the external / slow index, and the second is the faster / internal index.

+17
source

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

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

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

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

Both results will lead to the following:

 [14,15,16,24,25,26,34,35,36] 
+12
source

If you really like to see for in your code, you can also do something like this:

 for :: [a] -> (a -> b) -> [b] for = flip map nested :: [Integer] nested = concat nested_list where nested_list = for [1, 2, 3] (\i -> for [4, 5, 6] (\j -> i * 10 + j ) ) 

You can also look at for and Identity for a more idiomatic approach.

+5
source

Nested loops correspond to nested applications of map or similar functions. First approach:

 notThereYet :: [[Integer]] notThereYet = map (\x -> map (\y -> x*10 + y) [4, 5, 6]) [1, 2, 3] 

This gives you nested lists that can be fixed in two ways. One of them is to use the concat :: [[a]] -> [a] function:

 solution1 :: [Integer] solution1 = concat (map (\x -> map (\y -> x*10 + y) [4, 5, 6]) [1, 2, 3]) 

Another is to use this built-in function:

 concatMap :: (a -> [b]) -> [a] -> [b] concatMap f xs = concat (map f xs) 

Using this:

 solution2 :: [Integer] solution2 = concatMap (\x -> map (\y -> x*10 + y) [4, 5, 6]) [1, 2, 3] 

Other people mentioned lists and the list monad, but they are really down to nested concatMap applications.

+1
source

Because the do notation and list comprehension are already mentioned. The only other option I know is the Control.Monad liftM2 combinator. This is the same as the previous ones.

 liftM2 (\ab -> a * 10 + b) [1..3] [4..6] 
+1
source

The general solution to concatenating two lists of integers is as follows:

 concatInt [] xs = xs concatInt xs [] = xs concatInt xs ys = [join xy | x <- xs , y <- ys ] where join xy = firstPart + secondPart where firstPart = x * 10 ^ lengthSecondPart lengthSecondPart = 1 + (truncate $ logBase 10 (fromIntegral y)) secondPart = y 

Example: concatInt [1,2,3] [4,5,6] == [14,15,16,24,25,26,34,35,36]

A more complex example: concatInt [0,2,10,1,100,200] [24,2999,44,3] == [24,2,999,44,3,224,22,2999,244,23,1024,102,10999,1044, 103,124,12, 1999,144,13,10024,1002,100999,10044,1003,20024,2002,200999,20044,2003]

0
source

All Articles