Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

:: a -> (a -> b) -> b operator (Haskell)

Tags:

haskell

Writing Haskell programs I found myself in need of an operator like this.

(|>) :: a -> (a -> b) -> b
(|>) = flip ($)
infixl 0 |>

I think it is useful when glueing many functions together.

tText cs = someFun cs   |>
           lines        |>
           map (drop 4) |>
           reverse

I prefer it over . because with |> the order in which the functions are applied is the same as the order in which the functions are written.

tText' cs = reverse      . 
            map (drop 4) . 
            lines        . 
            someFun $ cs

Question is: is this (|>) something that already exists in the Prelude / some other basic library? Reimplementing simple stuff is something silly which I would like to avoid.

A Hoogle search did not help. Closest thing I found was >>> (Arrows), but it seems an overkill.

like image 893
user2205541 Avatar asked Mar 24 '13 21:03

user2205541


3 Answers

No, there isn't anything in a standard library that I know of. Years and years ago a lot of my code imported my breif but handy Forwards module:

> module Forwards where

> infixl 0 |>
> infixl 9 .>

> (|>) = flip ($)
> (.>) = flip (.)

I even used the same name as you!

These days I don't use it much at all - I got used to the order that function composition uses.

Feel free to use your own handy shortcuts.

I also use $ less than I used to. Where I used to write

thing = this $ that arg $ an other $ it

Now I write

thing = this . that arg . an other $ it
like image 138
AndrewC Avatar answered Oct 29 '22 12:10

AndrewC


The lens library defines this operator as &.

like image 25
John Wiegley Avatar answered Oct 29 '22 13:10

John Wiegley


You can also define (|>) as "flip id", and understanding why this works is a great lesson in type inference by unification as used in Haskell.

like image 33
pmk Avatar answered Oct 29 '22 12:10

pmk