Functional Style Coding in Julia

Out of the box it is not practical to chain a large number of function calls in Julia. Typical Julia style programming looks more like imperative programming.

However there are ways of doing this if you really want to. Out of the box I would write something like this:

filter(x -> x % 20 == 0,
filter(x -> length(string(x)) == 2,
filter(x -> x <= 170, (1:50) * 4)))

I don’t know Scala well enough to interpret exactly what you do in the rest of the code, and there is probably nothing like zip by index in the Julia standard library.

Anyway, what you can see from my example, is that while you get it in reverse order, because the lamda comes first, the actions you do in the data lines up quite well.

I admit it is not perfect and I would normally just split this up, but if this is really important to you Julia macros gives you a lot of opportunity to make syntax yourself that you prefer. There are several Julia packages demonstrating this.

Here is an example from the Lazy.jl package made for lazy functional programming:

isprime(n) =
@>> primes begin
takewhile(x -> x<=sqrt(n))
map(x -> n % x == 0)
any; !

This shows chaining in the sequence you want it. Alternatively if you want a more Microsoft LINQ style syntax you can get that as well, as shown in the Query.jl package:

x = @from i in df begin
@where i.age>50
@select {, i.children}
@collect DataFrame

Julia is in fact quite good IMHO at processing collections of data because of the special dot syntax. You can take any function defined for a single element and make it process multiple elements by adding a dot. Here is a contrived example:

julia> string.("0x", max.(4, 1:8))
8-element Array{String,1}:

The max function will perform the max of 4 and values in the range 1 to 8, consequtively. The string function will preprend “0x” to each element produced by the max function. So max(a, b) compares to scalar values a and b. But max.(a, b) will check if any argument is collection and then apply it pairwise for two collections or compare the scalar value to each value in the collection.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store