8

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.

Eli Sadoff
  • 7,173
  • 6
  • 33
  • 61

2 Answers2

19

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
Fengyang Wang
  • 11,901
  • 2
  • 38
  • 67
15

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
mbauman
  • 30,958
  • 4
  • 88
  • 123
  • 1
    And note that, in Haskell, it would [often be more idiomatic](http://stackoverflow.com/q/3030675/237428) to write `sin . sqrt . abs $ f 2`, where `.` is the same as Julia's `∘`, so they're even more similar :-) – Antal Spector-Zabusky Jan 19 '17 at 06:19
  • Or he can just define it himself as a stopgap solution: `∘(f::Function, g::Function) = (xs...) -> f(g(xs...))`. While not certain how it works in Haskell, note that you can now define a new compound anonymous function like this: `h = f∘g`. When I tried to do `cos $ sin` with no input in Haskell, I got an error. – DNF Jan 19 '17 at 08:55
  • @DNF that's because `$` in Haskell is function application (`f $ x = f x`) rather than function composition, which is written as `f . g = \x -> f (g x)`. – Cubic Jan 19 '17 at 11:07