Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flipped / reversed fmap (<$>)?

I found defining the following

(%)  = flip fmap

I can write code like this:

readFile "/etc/passwd" % lines % filter (not . null)

To me it makes more sense than the alternative:

filter (not . null) <$> lines <$> readFile "/etc/passwd"

Obviously, it's just a matter of order.

Does anyone else do this? Is there a valid reason not to write code like this?

like image 547
James Avatar asked Nov 05 '09 03:11

James


5 Answers

Your operator (%) is exactly the operator (<&>) from the lens package.

It can be imported with:

import Control.Lens.Operators ((<&>))
like image 186
2 revs, 2 users 75% Avatar answered Oct 05 '22 21:10

2 revs, 2 users 75%


(<&>) :: Functor f => f a -> (a -> b) -> f b 

Now available from Data.Functor in base.

https://hackage.haskell.org/package/base-4.12.0.0/docs/Data-Functor.html#v:-60--38--62-

like image 23
Chris Stryczynski Avatar answered Oct 05 '22 20:10

Chris Stryczynski


There is a similar function for the Applicative type class called <**>; it's a perfectly reasonable thing to want or use for Functor as well. Unfortunately, the semantics are a bit different for <**>, so it can't be directly widened to apply to Functor as well.

like image 34
bdonlan Avatar answered Oct 05 '22 21:10

bdonlan


-- (.) is to (<$>) as flip (.) is to your (%).  

I usually define (&) = flip (.) and it's just like your example, you can apply function composition backwords. Allows for easier to understand points-free code in my opinion.

like image 24
codebliss Avatar answered Oct 05 '22 21:10

codebliss


Personally I wouldn't use such an operators because then I have to learn two orders in which to read programs.

like image 20
Martijn Avatar answered Oct 05 '22 20:10

Martijn