[Haskell-beginners] \x -> x < 0.5 && x > -0.5

Michael Mossey mpm at alumni.caltech.edu
Mon Oct 19 22:48:50 EDT 2009



Carl Cravens wrote:
> Michael Mossey wrote:
>> Is there a nifty way to write
>>
>> filter (\x -> x < 0.5 && x > -0.5) xs
>>
>> without explicitly using x?
> 
> I'm pretty new to Haskell... are you looking for a *better* way to write 
> this, or is this an exercise in exploring alternatives for the sake of 
> understanding?
> 

Hi Carl,

Either one.

Let me chime in with some observations from a few months of studying 
Haskell. (Brent and Apfelmus can probably elaborate on this.)

Eliminating variables and working with function combinations has benefits. 
The one suggestion I've seen here that seems to be right on the money is

liftM2 (&&) (< 0.5) (> -0.5)

Although that might seem less clear to a beginner, it is actually _more_ 
clear than the lambda function in some ways. It's easier to work with proof 
at a more abstract level like this, and strange as it may seem, what I seem 
to observe in expert users of Haskell is that their brains will pick up 
what this is doing faster than the lambda function.

Or maybe this example is too small to be meaningful, but this kind of 
abstraction is the direction I want to move in, for there are benefits 
waiting for me when I arrive.

The Parsec library is an example of how concise and elegant code can get 
when you choose your abstractions carefully.



-Mike



More information about the Beginners mailing list