Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

haskell

julia

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.

like image 599
Eli Sadoff Avatar asked Jan 19 '17 04:01

Eli Sadoff


2 Answers

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
like image 132
Fengyang Wang Avatar answered Sep 23 '22 05:09

Fengyang Wang


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
like image 42
mbauman Avatar answered Sep 22 '22 05:09

mbauman