Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find if item is contained in Dict in Julia

I'm fairly new to Julia and am trying to figure out how to check if the given expression is contained in a Dict I've created.

function parse( expr::Array{Any} )
   if expr[1] == #check here if "expr[1]" is in "owl"
       return BinopNode(owl[expr[1]], parse( expr[2] ), parse( expr[3] ) )
   end
end

owl = Dict(:+ => +, :- => -, :* => *, :/ => /)

I've looked at Julia's documentation and other resources, but can't find any answer to this.

"owl" is the name of my dictionary that I'm trying to check. I want to run the return statement should expr[1] be either "+,-,* or /".

like image 667
Jet.B.Pope Avatar asked Nov 17 '25 04:11

Jet.B.Pope


1 Answers

A standard approach to check if some dictionary contains some key would be:

:+ in keys(owl)

or

haskey(owl, :+)

Your solution depends on the fact that you are sure that 0 is not one of the values in the dictionary, which might not be true in general. However, if you want to use such an approach (it is useful when you do not want to perform a lookup in the dictionary twice: once to check if it contains some key, and second time to get the value assigned to the key if it exists) then normally you would use nothing as a sentinel and then perform the check get_return_value !== nothing (note two = here - they are important for the compiler to generate an efficient code). So your code would look like this:

function myparse(expr::Array{Any}, owl) # better pass `owl` as a parameter to the function
   v = get(expr[1], owl, nothing)
   if v !== nothing
       return BinopNode(v, myparse(expr[2]), myparse(expr[3]))
   end
   # and what do we do if v === nothing?
end

Note that I use myparse name, as parse is a function defined in Base, so we do not want to have a name clash. Finally your myparse is recursive so you should define a second method to this function handling the case when expr is not an Array{Any}.

like image 99
Bogumił Kamiński Avatar answered Nov 19 '25 19:11

Bogumił Kamiński