Can we evaluate z3py expressions from a string? - z3py

I could not find anything on the subject in the docs. I tried like : s.add("Or(a==1, a==2, a==3), Or(b==1, b==2, b==3), Or(c==1, c==2, c==3)"), but that is not working. Is it possible?
In sympy we can do this with sympify or parse_expr
Edit:
I see I can use just pythons eval. It also has parse_smt2_string(), but no reference how SMT2 works.

eval is the way to go. There's no support in z3py in any way to parse what's essentially a Python program. Note that for that to work, you should somehow have the variables a/b and c in the environment, either by explicit declaration or by eval'ing their declarations from a string like "a, b, c = Ints('a b c')"
Regarding your comment "No reference how SMT2 works:" SMTLib is the standard format accepted by all SMT-solvers, including z3. See here: http://smtlib.cs.uiowa.edu/

Related

Difference between `->` and `lambda` in ruby [duplicate]

Pretty short question: Is it possible to use the Symbol#to_proc shorthand (e.g. lambda(&:upcase) with the stabby lambda syntax in Ruby? For example, I can say this:
p = lambda &:upcase
to get a Proc in p but I can't find an equivalent using ->. This:
p = -> &:upcase
doesn't work, of course.
Apparently, it is not supported.
I think it has something to do with the fact that proc and lambda are actually methods, and not keywords. They support the same features that we usually associate with each and the other methods from the Enumerable module. However, -> is a special language construct which is parsed separately.
I can't think of a reason why something like -> &:method shouldn't be possible, but as of now the syntax of the Ruby language simply doesn't allow it.

Ruby evaluate without eval?

How could I evaluate at mathematical string without using eval?
Example:
mathstring = "3+3"
Anyway that can be evaluated without using eval?
Maybe something with regex..?
You must either or eval it, or parse it; and since you don't want to eval:
mathstring = '3+3'
i, op, j = mathstring.scan(/(\d+)([+\-*\/])(\d+)/)[0] #=> ["3", "+", "3"]
i.to_i.send op, j.to_i #=> 6
If you want to implement more complex stuff you could use RubyParser (as #LBg wrote here - you could look at other answers too)
I'm assuming you don't want to use eval because of security reasons, and it is indeed very hard to properly sanitize input for eval, but for simple mathematical expressions perhaps you could just check that it only includes mathematical operators and numbers?
mathstring = "3+3"
puts mathstring[/\A[\d+\-*\/=. ]+\z/] ? eval(mathstring) : "Invalid expression"
=> 6
You have 3 options:
In my honest opinion best - parse it to Reverse Polish Notation and then parse it as equation
As you say use RegExps
Fastest, but dangerous and by calling eval but not Kernel#eval
RubyVM::InstructionSequence.new(mathstring).eval
Sure--you'd just want to somehow parse the expression using something other than the bare Ruby interpreter.
There appear to be some good options here: https://www.ruby-toolbox.com/search?q=math
Alternatively, it probably wouldn't be that hard to write your own parser. (Not that I've seriously tried--I could be totally full of crap.)
Dentaku seems (I haven't used it yet) like a good solution - it lets you check your (mathematical and logical) expressions, and to evaluate them.
calculator = Dentaku::Calculator.new
calculator.evaluate('kiwi + 5', kiwi: 2)

ruby: name of this syntax, which splits positional argument of block

I see a piece of code today
#! cruby 1.9
lam = lambda do |(a,b),c|
#blahblah
end
It seemingly equals to
lam = lambda do |l,c|
a,b = *l
#blahblah
end
Are there 'official name' for this syntax?
Yes, it is called destructuring.
So what is destructuring? The most concise definition I found is from Common Lisp the Language. Destructuring allows you to bind a set of variables to a corresponding set of values anywhere that you can normally bind a value to a single variable. It is a powerful feature of Clojure that lets you write some very elegant code. For more information about Clojure's features, I recommend you check out Jay Field's blog post on the subject. While destructuring in Ruby is not quite as powerful as Clojure, you can still do some cool stuff.

Mathematica: conditional "compilation"

I'm trying to make a conditinal expression which would initialize some functions, variables etc.. Something which would look like this in C:
#if option==1
int foo(int x){/*some code here*/}
int q=10;
#else
char foo(int x){/*some other code*/}
double q=3.141592;
#endif
use_q(q);
f(some_var);
In Mathematica I've tried using If, like this:
If[option==1,
foo[x_]=some_expression1;
q=10;
,
foo[x_]=some_expression2;
q=3.141592;
]
use_q[q];
f[some_var];
But the result is that functions' arguments are colored red, and nothing gets initialized or computed inside If.
So, how should I do instead to get conditional "compilation"?
Several things:
Do not use blanks (underscores) in variable names - in Mathematica these are reserved symbols, representing patterns.
In case you condition does not evaluate to True or False, If does not evaluate either.
Thus:
In[12]:= If[option==1,Print["1"],Print["Not 1"]]
Out[12]= If[option==1,Print[1],Print[Not 1]]
thus your result. Red colred arguments are not the issue in this particular case. You should either use === in place of ==, or TrueQ[option==1], to get what you want. Have a look here, for more information.
This sounds like something that would be better done as a function with an option, for example
Options[myfunction,{Compiled->False}]
myfunction[x_,opts:OptionsPattern[]]:=
With[{comp= TrueQ[OptionValue[Compiled]]},
If[comp, compiledFunction[x], notcompiledFunction[x] ]]
(The local constant comp within the With statement is not strictly necessary for this example but would be useful if your code is at all complex and you use this conditional more than once.)
I do not recommend defining different cases of a function inside an If[] statement. You would be better off using the built-in pattern-matching abilities in Mathematica. (See documentation here and especially here.)
Some useful documentation on options within functions can be found here, here and here.

Sprintf equivalent in Mathematica?

I don't know why Wikipedia lists Mathematica as a programming language with printf. I just couldn't find the equivalent in Mathematica.
My specific task is to process a list of data files with padded numbers, which I used to do it in bash with
fn=$(printf "filename_%05d" $n)
The closest function I found in Mathematica is PaddedForm. And after some trial and error, I got it with
"filename_" <> PaddedForm[ Round##, 4, NumberPadding -> {"0", ""} ]&
It is very odd that I have to use the number 4 to get the result similar to what I get from "%05d". I don't understand this behavior at all. Can someone explain it to me?
And is it the best way to achieve what I used to in bash?
I wouldn't use PaddedForm for this. In fact, I'm not sure that PaddedForm is good for much of anything. Instead, I'd use good old ToString, Characters and PadLeft, like so:
toFixedWidth[n_Integer, width_Integer] :=
StringJoin[PadLeft[Characters[ToString[n]], width, "0"]]
Then you can use StringForm and ToString to make your file name:
toNumberedFileName[n_Integer] :=
ToString#StringForm["filename_``", toFixedWidth[n, 5]]
Mathematica is not well-suited to this kind of string munging.
EDIT to add: Mathematica proper doesn't have the required functionality, but the java.lang.String class has the static method format() which takes printf-style arguments. You can call out to it using Mathematica's JLink functionality pretty easily. The performance won't be very good, but for many use cases you just won't care that much:
Needs["JLink`"];
LoadJavaClass["java.lang.String"];
LoadJavaClass["java.util.Locale"];
sprintf[fmt_, args___] :=
String`format[Locale`ENGLISH,fmt,
MakeJavaObject /#
Replace[{args},
{x_?NumericQ :> N#x,
x : (_Real | _Integer | True |
False | _String | _?JavaObjectQ) :> x,
x_ :> MakeJavaExpr[x]},
{1}]]
You need to do a little more work, because JLink is a bit dumb about Java functions with a variable number of arguments. The format() method takes a format string and an array of Java Objects, and Mathematica won't do the conversion automatically, which is what the MakeJavaObject is there for.
I've run into the same problem quite a bit, and decided to code my own function. I didn't do it in Java but instead just used string operations in Mathematica. It turned out quite lengthy, since I actually also needed %f functionality, but it works, and now I have it as a package that I can use at any time. Here's a link to the GitHub project:
https://github.com/vlsd/MathPrintF
It comes with installation instructions (really just copying the directory somewhere in the $Path).
Hope this will be helpful to at least some.
You could also define a function which passes all arguments to StringForm[] and use IntegerString or the padding functions as previously mentioned:
Sprintf[args__] := StringForm[args__] // ToString;
file = Sprintf["filename_``", IntegerString[n, 10, 5]];
IntegerString does exactly what you need. In this case it would be
IntegerString[x,10,5]
I agree with Pillsy.
Here's how I would do it.
Note the handy cat function, which I think of as kind of like sprintf (minus the placeholders like StringForm provides) in that it works like Print (you can print any concatenation of expressions without converting to String) but generates a string instead of sending to stdout.
cat = StringJoin##(ToString/#{##})&;
pad[x_, n_] := If[StringLength#cat[x]>=n, cat[x],
cat##PadLeft[Characters#cat[x],n,"0"]]
cat["filename_", pad[#, 5]]&
This is very much like Pillsy's answer but I think cat makes it a little cleaner.
Also, I think it's safer to have that conditional in the pad function -- better to have the padding wrong than the number wrong.

Resources