Is there an inverse of the Haskell $ operator?

守給你的承諾、 提交于 2019-12-03 06:18:57

问题


A quick question, is there an operator in Haskell that works like the dollar sign but gives precedence to the left hand side. I.E. instead of

f (x 1) 

being written as

f $ x 1

I'd like to write it as

x 1 $ f

This is purely a stylistic thing. I'm running a sequence of functions in order and it would be nice if I could write them left to write to match that I read left to write. If there an operator for this?

[update] A couple of people have asked if I can't define my own. In answer, I wanted to check there wasn't an existing operator before I reinvented the wheel.


回答1:


As of GHC 7.10 (base 4.8.0.0), & is in Data.Function: https://hackage.haskell.org/package/base-4.8.0.0/docs/Data-Function.html




回答2:


In Haskell you can use flip to change arguments' order of any binary function or operator:

ghci> let (|>) = flip ($)
ghci> 3 |> (+4) |> (*6)
42



回答3:


I do not know, whether there is an standart operator, but what prevents you from writing your own? This works in ghci:

Prelude> let a $> b = b a
Prelude> 1 $> (+2)
3
Prelude> sum [1, 2] $> (+2)
5
Prelude> map (+2) [1, 2] $> map (+3)
[6,7]

UPDATE: searching on hoogle for a -> (a -> b) -> b (it is the type of this operator) found nothing useful.




回答4:


This combinator is defined (tongue in cheek) in the data-aviary package:

Prelude Data.Aviary.BirdsInter> 1 `thrush` (+2)
Loading package data-aviary-0.2.3 ... linking ... done.
3

Although actually using that package is a rather silly thing to do, reading the source is fun, and reveals that this combinator is formed via the magic incantation of flip id (or, in ornithological parlance, cardinal idiot).




回答5:


I am not aware of any standard version, but I've seen (#) used for that purpose in a couple places. The one in particular that comes to mind is HOC, which uses it in an idiom like:

someObject # someMessage param1 param2

I seem to recall seeing other "object-oriented" libraries using the # operator in the same way, but cannot remember how many or which ones.




回答6:


Can't you just redefine $.

let ($) x f = f x

Or just choose a different operator, like $$



来源:https://stackoverflow.com/questions/4090168/is-there-an-inverse-of-the-haskell-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!