<br><br><div class="gmail_quote">2009/2/7 Cory Knapp <span dir="ltr"><<a href="mailto:thestonetable@gmail.com">thestonetable@gmail.com</a>></span><br><div><br><nice explanation on : operator - always useful> <br>
</div><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;"><br>
Does that help, or did I miss the point?<br>
<br></blockquote><div>Ok, I'll try to be more clear with an example: the following function - which surely can be written in better way - takes a list and a predicate and builds two lists. a list of lists of consecutive elements that satisfy the predicate and a list of separators, i.e. of elements that does not satisfy the predicate. <br>
</div></div>That is: groups odd [1,3,2,5,9,6] -> [[1,3],[5,9]], [2,6]<br>The function uses another function, groupWhile, which works like takeWhile but returns also the rest of the list.<br><br>Now, from the way the function works, it shoud build the two result lists by appending new elements to them.<br>
But, as you said, appending is expensive in haskell, so instead I build the lists using (:), which gives me the list<br>in reverse order, and then I use the 'final step' of the function - the base case of the recursion - to reverse the<br>
result. If I understand lazyness, this should be a low-cost operation because it does not actual build a reversed<br>list, but only make the list to be 'consumed' from the tail.<br><br>Now, this trick is not mine: I read it somewhere on internet (I can'tremember where), so I was asking if it is classified among the 'neat tricks' or among the 'ugly hacks' :-)<br>
<br>Here is the code I was referring to:<br><br><br>groups :: (a->Bool)-> [a] -> ([[a]],[a])<br>groups f lst = groups_ f ([],[]) lst where<br> groups_ f (gs,seps) [] = (reverse gs, reverse seps)<br> groups_ f (gs,seps) [a] = if (f a) <br>
then ( reverse ( [a]:gs), reverse seps )<br> else ( reverse gs , reverse (a:seps) )<br> groups_ f (gs, seps) lst = groups_ f (g:gs, r:seps) est <br> where<br>
(g, (r:est)) = groupWhile f lst<br><br>Ciao<br>-------<br>FB<br><br><br>