Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method Chaining in Julia

Tags:

julia

I read https://github.com/JuliaLang/julia/issues/5571 which made me think I could break lines like that due to some of the comments:

a = [x*5 for x in 0:20 if x>4]

scale(y) = (x)-> y*x
filter(y) = x -> [z for z in x if z>y]

a|>(x->x/3)
    |>scale(2)
    |>filter(4)
    |>println

But I get the error:

ERROR: LoadError: syntax: "|>" is not a unary operator
 in include_from_node1(::String) at ./loading.jl:488
 in process_options(::Base.JLOptions) at ./client.jl:265
 in _start() at ./client.jl:321

Am I forced to use a|>(x->x/3)|>scale(2)|>filter(4)|>println?

like image 627
Thomas E Avatar asked Jun 13 '17 11:06

Thomas E


People also ask

What is a method in Julia?

The feature of Julia that allows the call of the right implementation of a function based on arguments is called multiple dispatch, and the implementations are referred to as methods. Each function may have a number of methods defined for various data types, and it may have no methods at all defined for some.

What is map in Julia?

The map() is an inbuilt function in julia which is used to transform the specified collection by using specified operation to each element.

What is Dot in Julia?

Julia defines corresponding dot operations for every binary operator. These are designed to work element-wise with collections of values (called vectorized). That is, the operator that is dotted is applied for each element of the collection.


1 Answers

You can move the |> operators to the line-ends:

julia> a|>(x->x/3)|>
       scale(2)|>
       filter(4)|>
       println

This syntax is because the parser needs to decide unambiguously when a statement ends.

(actually, I've asked a question about such an issue myself and got a good answer. see Why is `where` syntax in Julia sensitive to new-line?)

like image 142
Dan Getz Avatar answered Sep 20 '22 15:09

Dan Getz