<div dir="ltr"><div class="gmail_extra"><div class="gmail_quote">On Sat, Apr 18, 2015 at 4:21 PM, Michael Orlitzky <span dir="ltr"><<a href="mailto:michael@orlitzky.com" target="_blank">michael@orlitzky.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left-width:1px;border-left-color:rgb(204,204,204);border-left-style:solid;padding-left:1ex"><span class="">On 04/18/2015 01:10 PM, martin wrote:<br>
> Am 04/17/2015 um 11:18 PM schrieb Michael Orlitzky:<br>
><br>
>> Why do you want to avoid recursion? You could rewrite this to use list indices if you really wanted to, but anything<br>
>> you come up with is going to be essentially recursive, only less safe<br>
><br>
> Thanks for the code sample and pointing out that there may not be any last dropped element.<br>
><br>
> I was wondering if there is  to achive the desired behavior by plugging together higher-order functions. This was the<br>
> only reason why I wanted to avoid explicit recursion.<br>
><br>
<br>
</span>Sure. Whenever you're processing a list and building up a return value,<br>
it's probably a (left) fold. But a fold would pointlessly process the<br>
rest of the list after it had stopped dropping elements, violating one<br>
of your criteria. And foldl is of course implemented recursively =)<br>
<br>
A "short-circuiting" version of foldl might exist in some library, but<br>
there are a few ways I can think of to implement it, so it might be hard<br>
to find.</blockquote><div><br></div><div>You don't need a left fold for this. It's a bit awkward but you can indeed just combine functions. Here's one way to write it that should not suffer from any sort of pointless list processing.</div><div><br></div><div>import Data.List (tails)<br></div><div>import Data.Maybe (listToMaybe)</div><div><br></div><div>dropWhileWithLast :: (a -> Bool) -> [a] -> (Maybe a, [a])</div><div>dropWhileWithLast f xs =</div><div>  -- Not partial. The last element of tails is [] and</div><div>  -- maybe False will guarantee a non-empty list.</div><div>  head .<br></div><div>  dropWhile (maybe False f . listToMaybe . snd) $<br></div><div>  zip (Nothing : map Just xs) (tails xs)</div><div> <br></div></div></div></div>