[Haskell-cafe] filterFirst

Dan Weston westondan at imageworks.com
Mon Jul 23 17:17:06 EDT 2007


If you find it tedious to pass parameters that never change, remember 
that you can access symbols defined in the enclosing environment 
(closure), freeing you from "passing it on" each time:

filterAlpha :: (a -> Bool) -> [a] -> [a]
filterAlpha f = filterAlpha'
   where filterAlpha' [] = []
         filterAlpha' (x:xs)
           | f x         = x : (filterAlpha' xs)
           | otherwise   =     (filterAlpha' xs)

As far as the primed version filterAlpha' is concerned, f is a global 
symbol. The argument list is just used for values that vary.

This will be your friend if the parameter list starts to stack up with 
more and more "reference" or "environment" inputs. It is also easier to 
see that f never changes if it is defined in only one spot.

Later, when you study monads you will notice the same pattern in the 
Reader monad, where the technique is even more valuable.

Dan Weston

Alexteslin wrote:
> 
> filterAlpha :: (a -> Bool) -> [a] -> [a]
> filterAlpha f [] = []
> filterAlpha f (x:xs)
> 	|f x   = x : filterAlpha f xs    -- corrected
> 	|otherwise = filterAlpha f xs    -- corrected




More information about the Haskell-Cafe mailing list