I need help understanding the following Haskell function,
split l = rr++[ll]
where
split = foldl
( \ (c,a) e ->
case c of
[] -> ([e],a)
_ -> if e*(head c) < 0
then ([e],a++[c])
else (c++[e],a))
([],[])
(ll,rr) = split l
> split [1,2,3,-1,-2,7,4,-3,-5,-6,2,3]
[[1,2,3],[-1,-2],[7,4],[-3,-5,-6],[2,3]]
It splits consecutive numbers with the same sign in separate lists as seen above. In Scheme, the tracer function was so helpful in evaluating expressions step by step, but unfortunately, GHCi doesn’t have such a feature. Please help me step through the code. Thanks!
Note: I understand the foldl part of the function. It is the pattern matching part (split l = rr++[ll] and (ll,rr) = split l) which really confuses me!
I think what may be confusing you here is that in fact the
splitinside thewhereis in fact entirely different from thesplitat the top level – the inner one “shadows” the outer one, just like local variables override global ones. The following code does the exact same thing:So we call
notSpliton the input list, which returns a tuple(ll,rr), then we calculaterr ++ [ll]and return that.(As my comment said above, the algorithm is needlessly obscure, inefficient, and incorrect on lists including zeroes. But that’s another issue entirely).