Thursday, May 29, 2008

Eschewing flip

I realized recently that I've developed a small dislike of the Haskell function flip, which reverses the order of arguments of a binary function:
mod 3 5 ==> 3
flip mod 3 5 ==> 2
flip is generally used in place of a lambda expression, when constructing a specialized function:
map (\x -> mod x 17) [1..] -- with lambda
map (flip mod 17) [1..] -- with flip
Unfortunately, my brain really doesn't like that reversal. When reading any non-trivial expression using flip, I have to stop and think about which argument is now where.

I've found that I prefer sections. You need to have one of the arguments handy, but I find that's often the case:
map (`mod` 17) [1..] -- with section
I like this form better because it preserves the visual ordering of the arguments, which seems to be deeply seated in my reasoning process. Because of Haskell's flexibility with switching between prefix and infix application, it's easy for me to adopt a style to suit this preference.


Antti-Juhani Kaijanaho said...

About the only place where I use flip a lot is to flip the arguments of map and mapM and similar functions (like flip map xs $ \ x -> ...).

(It's weird that Blogger does not allow me to use <tt> in a comment.)

Clifford Beshers said...

I used to do that, but found even my own code hard to read, so I now write that:
(`map` xs) \x -> ...

Antti-Juhani Kaijanaho said...

(`map` xs) looks even less obvious to me, it would never occur to me to use it, probably because map is not usually used as an infix operator. If I find flip map problematic, I usually just define foreach = flip map :)

Clifford Beshers said...

Sensible. I wrote the blog in part because I figured my style was unusual.

Now that I think about it, in that situation I would probably just use a where clause, e.g., map f xs ... where f.

I think a better example of where I'd use the section would be in the middle of a composition pipeline, just can't think of an example right now.

In any case, I don't think there's anything wrong with using flip, it's just that I have never managed to get to the point where reading it is automatic.

Derek Wong said...

So this is probably utterly random (or pseudo-random since I didn't actually randomly press keys to arrive here), but I worked at Linspire about 4-5 years ago when you were the lead for the OS team. All I did was test some things out (aka I had no standing there and would not be surprised if you couldn't pick me out of a lineup).

However this is how I got here:

-I've been recently been interested in FP

-was reading on Wikipedia

-reminded of David Fox using OCaml
looked for him

-found seereason and gerboa

-found you because of your associations with those projects

After all of that, just wanted to leave a note even though this blog doesn't look particularly active.