On Thu, Mar 16, 2023, 20:33 Todd Wilson <twilson at csufresno.edu> wrote:> ...> My question: can we do better than this? It seems that this solution is
> constantly building and breaking apart pairs. (Or is it, when optimized?)I don't think we can do better (as others have commented). Laziness is a benefit for peeling off only the beginning(s) of possibly-infinite (sub-)lists.
I believe that there is more to say about this function "runs"
than just concentrate on the issue of rebuilding the result list.
This is one of quite classical pedagogical exercises in list
processing in Haskell, and has been discussed at least twice on
StackOverflow
E.g.,
Such recursive schemas as proposed by Todd Wilson should be -- of
course -- mastered, but, suppose that your students have already
heard about combinators, and all them zips, folds, maps, etc. ,
and they need now some training. What about the following?
runs xs = ru (zip xs (False : zipWith (<) xs (tail xs)))
where
ru (z:zq) =
let (a,b) = span snd zq
in (map fst (z:a) : ru b)
ru [] = []
When I gave this exercise (some centuries ago), I didn't care
about having manufactured auxiliary structures, but I gently
asked the students to understand this code, to
realize that it is easy to "transmute" a (binary) relation between
neighbours in a list into a unary predicate, which could then be
used by span.
Jerzy Karczmarczuk