53

If I want to apply f first and g second, I have to write:

g . f

Is there another standard syntax that would allow me to write the functions in the reverse order?

f <whatever> g

I know I can just invent my own syntax:

compose f g x = g (f x)

and then use it like this:

f `compose` g

But I would rather use a standard library facility.

fredoverflow
  • 256,549
  • 94
  • 388
  • 662

2 Answers2

59

f >>> g from Control.Arrow.

MasterMastic
  • 20,711
  • 12
  • 68
  • 90
Josh Lee
  • 171,072
  • 38
  • 269
  • 275
  • 1
    Thanks, the change from `.` to `>>>` really made my particular piece of code much easier to understand :) By the way, I'm not too familiar with arrows, but I take it `>>>` is much more general than `.`, right? – fredoverflow Aug 26 '11 at 17:52
  • 6
    I was hoping this would show up if I Hoogled "(a -> b) -> (b -> c) -> a -> c". Alas, Hoogle is not quite clever enough. – Daniel Pratt Aug 26 '11 at 17:54
  • 2
    @FredOverflow: `<<<` and `>>>` are defined for the `Category` class, which is indeed more general. All `Arrow` instances are `Category` instances, including the familiar `(->)`. On the other hand, the whole point of `Arrow` and `Category` is to generalize things that compose end-to-end given matching types, like functions do, so you don't need to worry too much about `Arrow`s as a whole here. – C. A. McCann Aug 26 '11 at 17:55
  • 2
    @Daniel Pratt: Alas, Hoogle won't match `(->)` against type constructor variables. It won't find anything for `(a -> b -> c) -> (a -> b) -> a -> c`, either. – C. A. McCann Aug 26 '11 at 17:57
  • 2
    @C. A. McCann: It's probably a result of the special treatment `(->)` gets with respect to reordering of arguments and so on. It's able to generalize other type constructor operators. – hammar Aug 29 '11 at 01:49
  • Neat, I guess, but I'd really rather not deal with all of the extra machinery of a category. I'll just define it myself, I guess. – enigmaticPhysicist May 17 '22 at 21:06
1

In addtition to >>>, some libraries provide their own version of this function, for example:

You may use Hoogle to find examples of functions with a specific signature. For your exact question you can use hoogle.haskell.org/?hoogle=(a -> b) -> (b -> c) -> (a -> c).

gregorias
  • 181
  • 9