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

Michael Mossey mpm at alumni.caltech.edu
Mon Oct 19 15:09:02 EDT 2009



Heinrich Apfelmus wrote:
> Michael Mossey wrote:
>> Is there a nifty way to write
>>
>> filter (\x -> x < 0.5 && x > -0.5) xs
>>
>> without explicitly using x?
>>
>> Maybe arrows? I have a vague understanding that arrows can "send" an
>> argument to more than one computation.
> 
> That's a job for the reader monad.
> 
> 
> Lambda Fu, form 53 - silent reader of truth
> 
>     import Control.Monad
>     import Control.Monad.Reader
> 
>     filter (liftM2 (&&) (< 0.5) (> -0.5)) xs
> 
> 

Cool.

I realized there was a way to think about this. I haven't used the reader 
monad in my own projects, but I recall it's one way to pass the same value 
into several functions:

headTail = do
   h <- head
   t <- tail
   return (h,t)

headTail "foo" = ('f',"oo")

Note also there's no need for runReader or evalReader (at least not that 
I'm aware of) because unlike other monads, the reader monad is itself a 
function that takes the state to be read.

This could be generalized to

headTail2 g = do
    h <- head
    t <- tail
    return $ g h t

headTail2 (,) "foo" = ('f',"oo")

But this form:  do { x <- m1; y <- m2; return $ g x y} is exactly the 
definition of liftM2.  Specifically, liftM2 g m1 m2.




More information about the Beginners mailing list