Johan Tibell johan.tibell at gmail.com
Wed Jul 18 04:02:21 EDT 2007

```I found myself wanting a map that looks at neighboring elements. This is
where I used explicit recursion the most. Something like this:

f [] = []
f ((Foo a) : (Bar b) : xs)
| fooBar a b = Foo a : f xs
| otherwise = Bar b : f xs

This is almost a map. A variation is when filtering and you want some
look-ahead to make the filtering decision. There's probably a good way to do
this I'm not aware of.

Johan

On 7/17/07, David F. Place <d at vidplace.com> wrote:
> You hardly ever need to use explicit recursion in Haskell.  Every
> useful way of doing recursion has already been captured in some
> higher order function.  For example here is your subarrays
> implemented using unfoldr:
>
> subarrays xs = concat \$ unfoldr f xs
>      where
>           f [] = Nothing
>           f xs = Just  ( [ys | n <- [1..length xs], ys <- [(take n
> xs)]], tail xs)
>
> On Jul 17, 2007, at 4:26 PM, James Hunt wrote:
>
> > Hi,
> >
> > As a struggling newbie, I've started to try various exercises in
> > order to improve. I decided to try the latest Ruby Quiz (http://
> > www.rubyquiz.com/quiz131.html) in Haskell. Would someone be kind
> > enough to cast their eye over my code? I get the feeling there's a
> > better way of doing it!
> >
> > subarrays :: [a] -> [[a]]
> > subarrays [] = [[]]
> > subarrays xs = (sa xs) ++ subarrays (tail xs)
> >  where sa xs = [ys | n <- [1..length xs], ys <- [(take n xs)]]
> >
> > maxsubarrays :: [Integer] -> [Integer]
> > maxsubarrays xs = msa [] (subarrays xs)
> >  where
> >    msa m [] = m
> >    msa m (x:xs)
> >      | sum x > sum m = msa x xs
> >      | otherwise     = msa m xs
> >
> > --for testing: should return [2, 5, -1, 3]
> > main = maxsubarrays [-1, 2, 5, -1, 3, -2, 1]
> >
> > to find any that teach you how to really "think" in a Haskell way.
> > Is there anything (books, online tutorials, exercises) that anyone
> > could recommend?
> >
> > Thanks,
> > James
> > _______________________________________________
>
>    ___________________
> (---o-------o-o-o---o-o-o----(
> David F. Place
> mailto:d at vidplace.com
>
>
> _______________________________________________