Here is my thought process for this problem ... We want to slice the list into & zquo; chain & rsquo; (so a list of lists), given the test, to see if the two elements are connected.
chains :: (x -> x -> Bool) -> [x] -> [[x]]
I donโt remember anything like that in the library, so I decided to quit my own. I want to determine the appropriate recursion strategy to handle the list.
Can I just think about the elements? Not. I quickly rule out map and foldMap , since the elements do not seem to be considered independently of each other in this issue.
Next, I ask & lsquo; Does output type have list algebra? & rsquo ;. This may not seem like an obvious thought formulated in this way, but it breaks down into the next reasonable question. Does nil & rsquo; and & lsquo; cons & rsquo; operations that form outputs (lists of circuits) instead of inputs (lists)? If so, I can use foldr to convert input nil-and-cons to output nil-and-cons, like this.
chains :: (x -> x -> Bool) -> [x] -> [[x]] chains link = foldr chCons chNil where -- chNil :: [[x]] -- chCons :: x -> [[x]] -> [[x]]
Clearly, there should be chNil as I group the source elements. Empty? It's empty!
chains :: (x -> x -> Bool) -> [x] -> [[x]] chains link = foldr chCons [] where -- chCons :: x -> [[x]] -> [[x]]
Can I write chCons ? Suppose I get a list of nets: how to add a new element? Well, if there is a cross chain to which I can connect, then I have to develop this chain, otherwise I have to start a new chain. Therefore, I have a special case for a non-empty circuit at the beginning of a non-empty circuit list, and by default - minus one.
chains :: (x -> x -> Bool) -> [x] -> [[x]] chains link = foldr chCons [] where chCons y ( xs@ (x : _) : xss) | link yx = (y : xs) : xss chCons y xss = [y] : xss
And we are at home!
> chains (\ xy -> x + 1 == y) [1,2,3,4,5,6,8,9,10] [[1,2,3,4,5,6],[8,9,10]]
The letter of operators has algebra for a given type, if you can implement these operators for values โโof this type. Constructors of a data type are just one algebra, one implementation of many operators, the construction of values โโin this very data type. A good way to compute with inputs from a data type is to implement your algebra for the desired type of outputs. The point of foldr is to fix this: find the algebra & rsquo; template, and itโs right for the money for this problem.