I’m new to the language, but somewhat experienced with the programming in general. I am learning from Julia Data Science book and I reached the section discussing filters. Having some issues understanding the material there, I checked the built-in help by typing ?filters
in the terminal. One of the examples is this:
julia> d = Dict(1=>"a", 2=>"b")
Dict{Int64, String} with 2 entries:
2 => "b"
1 => "a"
julia> filter(p->isodd(p.first), d)
Dict{Int64, String} with 1 entry:
1 => "a"
Now, I’m completely baffled by the first argument in the filter(p->isodd(p.first), d)
. So, as per the documentation,
filter(f, d::AbstractDict)
removes elements for whichf
isfalse
.
p->isodd(p.first)
looks like an anonymous function. I am performing isodd(p.first)
on parameter p
. What does the parameter p
represent here? is it the key, the value, or the pair?
Next, Base.isodd
documentation says that isodd
returns a boolean based on the number argument, isodd(x::Number) -> Bool
. From this I understand that p.first
is a number, and the only numbers I have in the Dict
are its keys. So here again I am confused by what p.first
does. Base.First
documentation doesn’t say anything useful. When I try to change .first
to .last
I get an error.
type Pair has no field last
so when I check Base.Pair documentation it says that
Pair
is treated as a single “scalar” for broadcasting operations
Is this what is happening here, is p.first
necessary because the whole key/value pair is treated as a single “scalar”? That’s as far as I got through deciphering this. So, 1 => "a"
is pair or “scalar” one = odd, bool is true, not removed, 2 => "b"
is pair two = even, bool is false, f
removes it? Please help me understand this. Even if this is true, why do I need .first
? Error when trying just p -> isodd(p)
that I’m missing a method for isodd
- again, nothing I can figure out from reading the Base.isodd
documentation.
And finally, is this really the best way to do it? I mean, can you filter Dict elements from this example in a less convoluted way? Do you have to go with the anonymous function and the obscure “scalar” behavior of the Core.Pair
objects when broadcasting? I’m asking honestly, this is all very beginner unfriendly. I would like to go through some more basic and logical with this example in hope to understand why this example has been set up this way.
Thanks in advance.