8

I am trying to understand this piece of code which returns the all possible combinations of [a] passed to it:

-- Infinite list of all combinations for a given value domain
allCombinations :: [a] -> [[a]]
allCombinations []     = [[]]
allCombinations values = [] : concatMap (\w -> map (:w) values)
                                        (allCombinations values)

Here i tried this sample input:

ghci> take 7 (allCombinations [True,False])
[[],[True],[False],[True,True],[False,True],[True,False],[False,False]]

Here it doesn't seems understandable to me which is that how the recursion will eventually stops and will return [ [ ] ], because allCombinations function certainly doesn't have any pointer which moves through the list, on each call and when it meets the base case [ ] it returns [ [ ] ]. According to me It will call allCombinations function infinite and will never stop on its own. Or may be i am missing something?

On the other hand, take only returns the first 7 elements from the final list after all calculation is carried out by going back after completing recursive calls. So actually how recursion met the base case here?

Secondly what is the purpose of concatMap here, here we could also use Map function here just to apply function to the list and inside function we could arrange the list? What is actually concatMap doing here. From definition it concatMap tells us it first map the function then concatenate the lists where as i see we are already doing that inside the function here?

Any valuable input would be appreciated?

Sniper
  • 395
  • 1
  • 8
  • The base case is only ever used if you pass an empty list as the parameter to `allCombinations`. It's never used in a recursive case. – 4castle Mar 21 '19 at 15:22
  • i.e. it is *not* a base case but a special case, and this is not a recursion but a corecursion, which *never* stops. nice code / question. :) – Will Ness Mar 21 '19 at 16:33
  • Side note: It's possible that this function could become much faster if you do value recursion instead of function recursion: `allCombinations values = let r = [] : concatMap (\w -> map (w:) values) r in r`. Haven't thought it through but this is one of the more powerful optimization opportunities. – luqui Mar 21 '19 at 19:20
  • @luqui actually, I make the opposite claim in my (updated) answer. Haven't tested it yet, though. – Will Ness Mar 22 '19 at 08:54

3 Answers3

8

Short answer: it will never meet the base case.

However, it does not need to. The base case is most often needed to stop a recursion, however here you want to return an infinite list, so no need to stop it.

On the other hand, this function would break if you try to take more than 1 element of allCombination [] -- have a look at @robin's answer to understand better why. That is the only reason you see a base case here.

The way the main function works is that it starts with an empty list, and then append at the beginning each element in the argument list. (:w) does that recursively. However, this lambda alone would return an infinitely nested list. I.e: [],[[True],[False]],[[[True,True],[True,False] etc. Concatmap removes the outer list at each step, and as it is called recursively this only returns one list of lists at the end. This can be a complicated concept to grasp so look for other example of the use of concatMap and try to understand how they work and why map alone wouldn't be enough.

This obviously only works because of Haskell lazy evaluation. Similarly, you know in a foldr you need to pass it the base case, however when your function is supposed to only take infinite lists, you can have undefined as the base case to make it more clear that finite lists should not be used. For example, foldr f undefined could be used instead of foldr f []

Lorenzo
  • 2,148
  • 7
  • 25
  • Thanks for detailed answer. The real confusion was how it took the first token [ ] to do the recursive calculation. You mean if its base case is undefined in case of infinite lists it will take [ ] as default base case ? And so it append [ [ ] ] at the end of the list to carry out the calculation? and if its return an infinite list which it does, how the control was transferred to Take function to only extract first 7 elements from an infinite list. I am just a beginner that is why i am trying to understand this from very basic level. :/ – Sniper Mar 21 '19 at 15:17
  • In Haskell it works the other way around. `take` has control, and it asks the function to compute the first 7 values. Also I edited my answer to explain that base case a bit better – Lorenzo Mar 21 '19 at 16:28
4

@Lorenzo has already explained the key point - that the recursion in fact never ends, and therefore this generates an infinite list, which you can still take any finite number of elements from because of Haskell's laziness. But I think it will be helpful to give a bit more detail about this particular function and how it works.

Firstly, the [] : at the start of the definition tells you that the first element will always be []. That of course is the one and only way to make a 0-element list from elements of values. The rest of the list is concatMap (\w -> map (:w) values) (allCombinations values).

concatMap f is as you observe simply the composition concat . (map f): it applies the given function to every element of the list, and concatenates the results together. Here the function (\w -> map (:w) values) takes a list, and produces the list of lists given by prepending each element of values to that list. For example, if values == [1,2], then:

(\w -> map (:w) values) [1,2] == [[1,1,2], [2,1,2]]

if we map that function over a list of lists, such as

[[], [1], [2]]

then we get (still with values as [1,2]):

[[[1], [2]], [[1,1], [2,1]], [[1,2], [2,2]]] 

That is of course a list of lists of lists - but then the concat part of concatMap comes to our rescue, flattening the outermost layer, and resulting in a list of lists as follows:

[[1], [2], [1,1], [2,1], [1,2], [2,2]]     

One thing that I hope you might have noticed about this is that the list of lists I started with was not arbitrary. [[], [1], [2]] is the list of all combinations of size 0 or 1 from the starting list [1,2]. This is in fact the first three elements of allCombinations [1,2].

Recall that all we know "for sure" when looking at the definition is that the first element of this list will be []. And the rest of the list is concatMap (\w -> map (:w) [1,2]) (allCombinations [1,2]). The next step is to expand the recursive part of this as [] : concatMap (\w -> map (:w) [1,2]) (allCombinations [1,2]). The outer concatMap then can see that the head of the list it's mapping over is [] - producing a list starting [1], [2] and continuing with the results of appending 1 and then 2 to the other elements - whatever they are. But we've just seen that the next 2 elements are in fact [1] and [2]. We end up with

allCombinations [1,2] == [] : [1] : [2] : concatMap (\w -> map (:w) values) [1,2] (tail (allCombinations [1,2]))

(tail isn't strictly called in the evaluation process, it's done by pattern-matching instead - I'm trying to explain more by words than explicit plodding through equalities).

And looking at that we know the tail is [1] : [2] : concatMap .... The key point is that, at each stage of the process, we know for sure what the first few elements of the list are - and they happen to be all 0-element lists with values taken from values, followed by all 1-element lists with these values, then all 2-element lists, and so on. Once you've got started, the process must continue, because the function passed to concatMap ensures that we just get the lists obtained from taking every list generated so far, and appending each element of values to the front of them.

If you're still confused by this, look up how to compute the Fibonacci numbers in Haskell. The classic way to get an infinite list of all Fibonacci numbers is:

fib = 1 : 1 : zipWith (+) fib (tail fib)

This is a bit easier to understand that the allCombinations example, but relies on essentially the same thing - defining a list purely in terms of itself, but using lazy evaluation to progressively generate as much of the list as you want, according to a simple rule.

Robin Zigmond
  • 14,041
  • 2
  • 16
  • 29
4

It is not a base case but a special case, and this is not recursion but corecursion,(*) which never stops.

Maybe the following re-formulation will be easier to follow:

allCombs :: [t] -> [[t]]
--        [1,2] -> [[]] ++ [1:[],2:[]] ++ [1:[1],2:[1],1:[2],2:[2]] ++ ...
allCombs vals = concat . iterate (cons vals) $ [[]]
    where
    cons :: [t] -> [[t]] -> [[t]]
    cons vals combs = concat [ [v : comb | v    <- vals]
                               |           comb <- combs ]

-- iterate   :: (a     -> a    ) -> a     -> [a]
-- cons vals ::  [[t]] -> [[t]]
-- iterate (cons vals)           :: [[t]] -> [[[t]]]
-- concat    ::                              [[ a ]] -> [ a ]
-- concat . iterate (cons vals)                      :: [[t]]

Looks different, does the same thing. Not just produces the same results, but actually is doing the same thing to produce them.(*) The concat is the same concat, you just need to tilt your head a little to see it.

This also shows why the concat is needed here. Each step = cons vals is producing a new batch of combinations, with length increasing by 1 on each step application, and concat glues them all together into one list of results.

The length of each batch is the previous batch length multiplied by n where n is the length of vals. This also shows the need to special case the vals == [] case i.e. the n == 0 case: 0*x == 0 and so the length of each new batch is 0 and so an attempt to get one more value from the results would never produce a result, i.e. enter an infinite loop. The function is said to become non-productive, at that point.

Incidentally, cons is almost the same as

                   == concat [ [v : comb | comb <- combs]
                               |           v    <- vals  ]
                   == liftA2 (:) vals combs

liftA2 :: Applicative f => (a -> b -> r) -> f a -> f b -> f r

So if the internal order of each step results is unimportant to you (but see an important caveat at the post bottom) this can just be coded as

allCombsA :: [t] -> [[t]]
--         [1,2] -> [[]] ++ [1:[],2:[]] ++ [1:[1],1:[2],2:[1],2:[2]] ++ ...
allCombsA   []   =  [[]]
allCombsA  vals  =  concat . iterate (liftA2 (:) vals) $ [[]]

(*) well actually, this refers to a bit modified version of it,

allCombsRes vals = res
             where res = [] : concatMap (\w -> map (: w) vals)
                              res
-- or:
allCombsRes vals = fix $ ([] :) . concatMap (\w -> map (: w) vals)
--  where
--  fix g = x where x = g x     -- in Data.Function

Or in pseudocode:

 Produce a sequence of values `res` by
      FIRST producing `[]`, AND THEN
      from each produced value `w` in `res`, 
          produce a batch of new values `[v : w | v <- vals]`
          and splice them into the output sequence
               (by using  `concat`)

So the res list is produced corecursively, starting from its starting point, [], producing next elements of it based on previous one(s) -- either in batches, as in iterate-based version, or one-by-one as here, taking the input via a back pointer into the results previously produced (taking its output as its input, as a saying goes -- which is a bit deceptive of course, as we take it at a slower pace than we're producing it, or otherwise the process would stop being productive, as was already mentioned above).

But. Sometimes it can be advantageous to produce the input via recursive calls, creating at run time a sequence of functions, each passing its output up the chain, to its caller. Still, the dataflow is upwards, unlike regular recursion which first goes downward towards the base case.

The advantage just mentioned has to do with memory retention. The corecursive allCombsRes as if keeps a back-pointer into the sequence that it itself is producing, and so the sequence can not be garbage-collected on the fly.

But the chain of the stream-producers implicitly created by your original version at run time means each of them can be garbage-collected on the fly as n = length vals new elements are produced from each downstream element, so the overall process becomes equivalent to just k = ceiling $ logBase n i nested loops each with O(1) space state, to produce the ith element of the sequence.

This is much much better than the O(n) memory requirement of the corecursive/value-recursive allCombsRes which in effect keeps a back pointer into its output at the i/n position. And in practice a logarithmic space requirement is most likely to be seen as a more or less O(1) space requirement.

This advantage only happens with the order of generation as in your version, i.e. as in cons vals, not liftA2 (:) vals which has to go back to the start of its input sequence combs (for each new v in vals) which thus must be preserved, so we can safely say that the formulation in your question is rather ingenious.

And if we're after a pointfree re-formulation -- as pointfree can at times be illuminating -- it is

allCombsY values =  _Y $ ([] :) . concatMap (\w -> map (: w) values)
    where
    _Y g = g (_Y g)      -- no-sharing fixpoint combinator

So the code is much easier understood in a fix-using formulation, and then we just switch fix with the semantically equivalent _Y, for efficiency, getting the (equivalent of the) original code from the question.

The above claims about space requirements behavior are easily tested. I haven't done so, yet.

See also:

Will Ness
  • 62,652
  • 8
  • 86
  • 167