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

Daniel Fischer daniel.is.fischer at web.de
Mon Oct 19 23:28:45 EDT 2009

```Am Dienstag 20 Oktober 2009 04:48:50 schrieb Michael Mossey:
> 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.

But it's not unconditionally a good thing. If you exaggerate it, it's pure obfuscation.
Nevertheless, playing around with eliminating variables and using combinators
even beyond the border of obfuscation is a good exercise.
You gain understanding and a feeling of when it's better to stop by that.

> The one suggestion I've seen here that seems to be right on the money is
>
> liftM2 (&&) (< 0.5) (> -0.5)

May I offer

(&&) <\$> (< 0.5) <*> (> -0.5)

? It works on Applicative Functors (doesn't need the full force of Monads).

>
> 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.

In this small example, both are immediately clear, you need more complicated lambda
expressions to get a measurable difference :)

```