Function chaining with |> and filter function

question

#1

How can I call filter(isodd) using function chaining |>?

This does not work:

julia> 1:9 |> filter(isodd)
ERROR: MethodError: no method matching filter(::typeof(isodd))
Closest candidates are:
  filter(::Any, ::Array{T,1} where T) at array.jl:2352
  filter(::Any, ::BitArray) at bitarray.jl:1637
  filter(::Any, ::AbstractArray) at array.jl:2313
  ...
Stacktrace:
 [1] top-level scope at none:0

I’m using Julia 1.0.1.


#2

The function chaining syntax only works if the function accepts a single argument. You can use an anonymous function for this purpose:

collect(1:9) |> x -> filter(isodd, x)

Although, subjectively I think that this is more readable:

filter(isodd, collect(1:9))

#3

Check out


And


#4

filter(::Function)::Function could return a function with single argument:

julia> import Base: filter

julia> filter(f::Function)::Function = x -> filter(f, x)
filter (generic function with 9 methods)

julia> 1:9 |> filter(isodd)
5-element Array{Int64,1}:
 1
 3
 5
 7
 9

#5

You can also use Query.jl’s @filter, which just works with pipelines.


#6

Just for more complet serie:

filter(1:9) do x; isodd(x) end