如何解决如何在 Julia 中没有不必要的括号的情况下进行评估?
我有一个 case 结构,它包含一个类型为 SymbolicUtils.Term{Bool}
的表达式。此外,我还定义了 SymbolicUtils
库中的规则,这些规则将这些案例作为输入并进行了简化。为了简化这些情况,形式应该是:(i == j) & (i == 3) & (j == 3) & (i == 3) & (j == 3)
没有不必要的括号。例如,拥有这个就不好:((i == j) & ((i == 3) & (j == 3))) & ((i == 3) & (j == 3))
为了解决这个问题,我想我可以将带有额外括号的表达式转换为字符串,然后我可以处理这个字符串以获得所需的形式。我实际上是这样做的:
function reduce_parentheses(case::Case)
main_exp_string = ""
exp_to_str = repr(case.condition) #Convert case's condition into a string.
condition_list = split(exp_to_str,"&") #Split cases to subcases into a list.
for i in 1:length(condition_list) # Iterate cases list one by one.
stripped = lstrip(condition_list[i],[' ']) #Remove the whitespace at the beginning of the expression.
stripped = rstrip(stripped,[' ']) #Remove the whitespace at the end of the expression.
stripped = lstrip(stripped,['(']) #Add opening parentheses at the beginning of the expression.
stripped = rstrip(stripped,[')']) #Add closing parentheses at the end of the expression.
#Get the desired form.
if i != 1
main_exp_string = main_exp_string * ' ' * '(' *stripped * ')'
elseif i == 1
main_exp_string = main_exp_string * '(' *stripped * ')'
end
if i != length(condition_list)
main_exp_string = main_exp_string * ' ' * '&'
end
end
println(main_exp_string)
exp = (Meta.parse(main_exp_string)) #Convert string back to an expression.
println(typeof(eval(exp))) #Convert expression back to SymbolicUtils.Term{Bool} type.
end
我可以得到所需形式的字符串,但是当我尝试将其转回表达式时,我得到了不同形式的不必要的括号,因为我认为它是从左到右计算的。
示例:
带有不必要括号的情况:((i == j) & ((i == 3) & (j == 3))) & ((i == 3) & (j == 3))
处理后的字符串(所需形式):(i == j) & (i == 3) & (j == 3) & (i == 3) & (j == 3)
评估案例:((((i == j) & (i == 3)) & (j == 3)) & (i == 3)) & (j == 3)
我该如何解决这个问题?也许我可以用更聪明的方式来代替将它转换为字符串?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。