Jet*_*ope 2 dictionary if-statement julia
我对 Julia 还很陌生,正在尝试弄清楚如何检查给定的表达式是否包含在我创建的 Dict 中。
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(:+ => +, :- => -, :* => *, :/ => /)
Run Code Online (Sandbox Code Playgroud)
我查看了 Julia 的文档和其他资源,但找不到任何答案。
“owl”是我要检查的字典的名称。我想运行 return 语句应该 expr[1] 是“+,-,* 或 /”。
检查某个字典是否包含某个键的标准方法是:
:+ in keys(owl)
Run Code Online (Sandbox Code Playgroud)
或者
haskey(owl, :+)
Run Code Online (Sandbox Code Playgroud)
您的解决方案取决于您确定这0不是字典中的值之一,这通常可能不正确。但是,如果您想使用这种方法(当您不想在字典中执行两次查找时,这很有用:一次检查它是否包含某个键,第二次获取分配给键的值,如果它存在)然后通常您将nothing用作哨兵然后执行检查get_return_value !== nothing(注意=这里的两个- 它们对于编译器生成有效代码很重要)。所以你的代码看起来像这样:
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
Run Code Online (Sandbox Code Playgroud)
请注意,我使用myparse名称,因为它parse是在 Base 中定义的函数,因此我们不希望发生名称冲突。最后你myparse是递归的,所以你应该为这个函数定义第二个方法来处理expr不是Array{Any}.