Eli Sadoff
Eli Sadoff

Reputation: 7308

Does Julia have an operator similar to Haskell's dollar sign?

Haskell's dollar sign is a wonderful function that for f $ g, for example, f is evaluated with the results of g as its argument. This can work brilliantly like this

sin $ sqrt $ abs $ f 2

Which is equivalent to

sin(sqrt(abs(f(2))))

The dollar sign is nice to me because it is more readable. I have noticed that Julia has |> which pipelines. This seems to do f |> g meaning that g takes the evaluated result of f as an argument. From what I have noticed, it seems that I could write the aforementioned expression like this

2 |> f |> abs |> sqrt |> sin

But I was wondering if there was some operator such that I could do something like what I did in Haskell.

Upvotes: 8

Views: 1017

Answers (2)

Fengyang Wang
Fengyang Wang

Reputation: 12051

One can define the $ operator (as long as you don't need its deprecated meaning of xor) locally in a module;

f $ y = f(y)

However, the associativity of this operator (it is left-associative) is incorrect, and its precedence is too high to be useful for avoiding brackets. Luckily, there are plenty of right-associative operators of the right precedence. One could define

f ← x = f(x)

(a single line definition, almost Haskell-esque!) and then use it thus:

julia> sin ← π
1.2246467991473532e-16

julia> exp ← sin ← π
1.0000000000000002

julia> exp ∘ sin ← π
1.0000000000000002

Upvotes: 19

mbauman
mbauman

Reputation: 31342

There's now a function composition operator on the unstable nightly version (soon to be in 0.6). It can be used on earlier versions with the Compat.jl package.

help?> ∘
"∘" can be typed by \circ<tab>

  f ∘ g

  Compose functions: i.e. (f ∘ g)(args...) means f(g(args...)). The ∘ symbol can be
  entered in the Julia REPL (and most editors, appropriately configured) by typing
  \circ<tab>. Example:

  julia> map(uppercase∘hex, 250:255)
  6-element Array{String,1}:
   "FA"
   "FB"
   "FC"
   "FD"
   "FE"
   "FF"

Or, with your example — note that you need parentheses here:

julia> (sin ∘ sqrt ∘ abs ∘ f)(2)
0.9877659459927356

Upvotes: 15

Related Questions