MiniZinc: print out generated constraints? - constraint-programming

With MiniZinc, is there a way to print out the programmatically-generated constraints? For example:
constraint exists (i in 1..3) (
foo != i
);
I want to confirm that it is generating:
constraint (foo != 1 \/ foo != 2 \/ foo !=3);

Although MiniZinc doesn't offer direct printing of constraints as such. MiniZinc does offer the trace(string: s, var $T: expr) function. Which can be used to debug your MiniZinc models. trace is a print-statement that prints its contents to the command line at the time of evaluation within the compiler. It can thus be used to print the information that you wish to see, but you'll have to format it yourself to show the constraints.
In the case of your exists loop you could use:
constraint exists(i in 1..3) (
trace("foo != \(i)" ++ if i != max(1..3) then " \\/ " else "\n" endif,
foo != i)
);
This will print foo != 1 \/ foo != 2 \/ foo != 3 to the command line.

To get to know the generated constraints, you can have a look at the generated FlatZinc file. The MiniZinc compiler translates the MiniZinc source into FlatZinc. This is then handed over to a solver back-end like Gecode of Chuffed.
MiniZinc input:
var int: foo;
constraint exists (i in 1..3) (
foo != i
);
solve satisfy;
Created FlatZinc:
var int: foo:: output_var;
var bool: X_INTRODUCED_0_ ::var_is_introduced :: is_defined_var;
var bool: X_INTRODUCED_1_ ::var_is_introduced :: is_defined_var;
var bool: X_INTRODUCED_2_ ::var_is_introduced :: is_defined_var;
constraint array_bool_or([X_INTRODUCED_2_,X_INTRODUCED_1_,X_INTRODUCED_0_],true);
constraint int_ne_reif(foo,1,X_INTRODUCED_0_):: defines_var(X_INTRODUCED_0_);
constraint int_ne_reif(foo,2,X_INTRODUCED_1_):: defines_var(X_INTRODUCED_1_);
constraint int_ne_reif(foo,3,X_INTRODUCED_2_):: defines_var(X_INTRODUCED_2_);
solve satisfy;
To look at the FlatZinc form, you can add parameter --output-fzn-to-stdout in the Configuration tab of the MiniZinc IDE:

MiniZinc goes through a whole series of steps when it compiles your expressions down to FlatZinc, so it's not so easy to decide after which step you would print the intermediate representation of the problem.
To look at the generated FlatZinc, you can also simply select "Compile" from the MiniZinc menu rather than using the --output-fzn-to-stdout command line option.

Related

How to compile QuasiQuoter during runtime?

I have a 'QuasiQuoter' which is useful in source code in Haskell, but also as a standalone application. So, I need to be able to run QuasiQuoter
During the compile time in Haskell - [myGrammar|someCommand|]
In runtime (runtime compilation) in shell - mygrammar 'someCommand'
The first part is easy but the second part might be a little clumsy if solved as calling the compiler with some generated code from the runtime.
I would like to solve a second part of the problem using some nice method in Haskell which doesn't accept only the source code, but accepts QuasyQuoter datatype instead so the code is less clumsy. But I can't find any compilation method like that.
Do you know any? Thanks.
Example of usage
Haskell
The function takes tuple [(a,b,c,d,e)] and returns a list of the strings with the products.
function = [lsql| {1..5}, r=[ a.* |> (*) ], "Product of a.1 * a.2 * ... * a.5 is &a.r"|]
Bash
The command reads from stdin csv with at least 5 numerical columns and returns a list of their products (one per line).
lsql-csv '-, r=[ a.* |> (*) ], "Product of a.1 * a.2 * ... * a.5 is &a.r"'
I think the question is how to parse and process a string in a uniform way between a quasiquoter and some other chunk of code. If this interpretation is right, then you just... do that. For example:
-- implementation of these is left to the reader, but can use standard Haskell
-- programming techniques and libraries, like parsec and ADTs and stuff
command :: Parser Command
interpret :: Command -> IO ()
jit :: Command -> Exp -- or Q Exp
Then, in your lsql-csv.hs, you would write something like
main = do
[s] <- getArgs
case parse command s of
Left err -> die (show err)
Right com -> interpret com
and in your LSql/CSV/QQ.hs, you would write something like
lsql = QuasiQuoter { quoteExp = \s -> case parse command s of
Left err -> qReport True (show err) >> fail ""
Right com -> return (jit com) -- or just jit com if that's already a Q Exp
}

does Template Haskell name quoting desugar 'x to NameG?

Can I always expect the single single-quote syntax to desugar to the NameG constructor? e.g. does
'x
always desugar to
(Name (OccName "x") (NameG VarName (PkgName "some-package") (ModName "SomeModule")))
This information must always be there, after name resolution, which is the stage Template Haskell runs after, right? And I haven't been able to quote local names, though I'm only interested in quoting top-level names.
Context: I want to write a function that returns the uniquely-qualified identifier. It's a partial function because I can't constrain the input, as Template Haskell doesn't have any GADTs or anything, while I don't want to wrap the output in uncertainty. And I don't want to use a quasi-quoter or splice, if ' will do. I want to prove that this partial function is safe at runtime when used as above, quoting top-level names in the same module, given:
name (Name occ (NameG _ pkg mod)) = Unique occ pkg mod
I want to have a function like:
(<=>) :: Name -> a -> Named a
given:
data Named a = Named a Unique
to annotate variable bindings:
x = 'x
<=> ...
without the user needing to use the heavy splice syntax $(name ...), and invoke splicing at compile time:
x = $(name 'x)
<=> ...
The user will be writing a lot of these, for configuration.
https://downloads.haskell.org/~ghc/7.8.3/docs/html/users_guide/template-haskell.html and https://hackage.haskell.org/package/template-haskell-2.8.0.0/docs/src/Language-Haskell-TH-Syntax.html#Name didn't say.
(p.s. I'd also like to know if the double single-quote syntax (e.g. ''T) had the analogous guarantee, though I'd expect them to be the same).
Since ' quoted names are known at compile time, why don't you change name to be in the Q monad:
name :: Name -> ExpQ
name (Name occ (NameG _ pkg mod)) = [| Unique occ pkg mod |]
name n = fail $ "invalid name: "++ gshow n
Then you use $(name 'show) :: Unique instead of name 'show :: Unique. If you get an invalid Name (say somebody uses mkName), that failure will show up at compile time.

Where are the magic rules for GHC assert?

http://hackage.haskell.org/package/base-4.6.0.1/docs/src/GHC-Base.html#assert seems to define assert to be a no-op. Where's the logic that turns this into something else when assertions are enabled?
The comment above that function gives a hint:
-- Assertion function. This simply ignores its boolean argument.
-- The compiler may rewrite it to #('assertError' line)#.
So, just use github code search and search for assertError: search results
This turns up the file RnExpr.lhs. Searching for assert in this file, you'll find the following code:
finishHsVar :: Name -> RnM (HsExpr Name, FreeVars)
-- Separated from rnExpr because it's also used
-- when renaming infix expressions
-- See Note [Adding the implicit parameter to 'assert']
finishHsVar name
= do { this_mod <- getModule
; when (nameIsLocalOrFrom this_mod name) $
checkThLocalName name
; ignore_asserts <- goptM Opt_IgnoreAsserts
; if ignore_asserts || not (name `hasKey` assertIdKey)
then return (HsVar name, unitFV name)
else do { e <- mkAssertErrorExpr
; return (e, unitFV name) } }
That's where it replaces assert by assertError, but only if assertions are enabled.
assertError is defined in GHC.IO.Exception

using where clause in haskell causing error?

I am new in haskell trying to do a small task
get1th ( a , _, _ , _) = a
foo input =
where input = (a:_,b:_,c:_,d:_)
if ( length (get1th input) == 2 )
then permutations[2]
else permutations[3]
I am getting error saying
parse error on input `where'
please give me a hint
where clause must be written at the end:
foo input =
if ( length (get1th input) == 2 )
then permutations[2]
else permutations[3]
where (a:_,b:_,c:_,d:_) = input
UPDATED
It is also require to swap to (a:_,b:_,c:_,d:_) = input, reason - we want to extract values, but not to redefine input
As #wit has pointed out, where should be used in the end of expression. Why? Because:
it is not a let;
because it is related with all the previous context (block) of the function.
If you want to define an alias fronthand, you should use the let expression.
For more information about the differences and advantages of them, see the Let vs. Where.

Use literal operators (eg "and", "or") in Groovy expressions?

My current work project allows user-provided expressions to be evaluated in specific contexts, as a way for them to extend and influence the workflow. These expressions the usual logical ones f. To make it a bit palatable for non-programmers, I'd like to give them the option of using literal operators (e.g. and, or, not instead of &, |, !).
A simple search & replace is not sufficient, as the data might contains those words within quotes and building a parser, while doable, may not be the most elegant and efficient solution.
To make the question clear: is there a way in Groovy to allow the users to write
x > 10 and y = 20 or not z
but have Groovy evaluate it as if it were:
x > 10 && y == 20 || !z
Thank you.
Recent versions of Groovy support Command chains, so it's indeed possible to write this:
compute x > 10 and y == 20 or not(z)
The word "compute" here is arbitrary, but it cannot be omitted, because it's the first "verb" in the command chain. Everything that follows alternates between verb and noun:
compute x > 10 and y == 20 or not(z)
───┬─── ──┬─── ─┬─ ───┬─── ─┬─ ──┬───
verb noun verb noun verb noun
A command chain is compiled like this:
verb(noun).verb(noun).verb(noun)...
so the example above is compiled to:
compute(x > 10).and(y == 20).or(not(z))
There are many ways to implement this. Here is just a quick & dirty proof of concept, that doesn't implement operator precedence, among other things:
class Compute {
private value
Compute(boolean v) { value = v }
def or (boolean w) { value = value || w; this }
def and(boolean w) { value = value && w; this }
String toString() { value }
}
def compute(v) { new Compute(v) }
def not(boolean v) { !v }
You can use command chains by themselves (as top-level statements) or to the right-hand side of an assignment operator (local variable or property assignment), but not inside other expressions.
If you can swap operators like > and = for the facelets-like gt and eq, respectively, i THINK your case may be doable, though it will require a lot of effort:
x gt 10 and y eq 20 or not z
resolves to:
x(gt).10(and).y(eq).20(or).not(z)
And this will be hell to parse.
The way #Brian Henry suggested is the easiest way, though not user-friendly, since it needs the parens and dots.
Well, considering we can swap the operators, you could try to intercept the Integer.call to start expressions. Having the missing properties in a script being resolved to operations can solve your new keywords problem. Then you can build expressions and save them to a list, executing them in the end of the script. It's not finished, but i came along with this:
// the operators that can be used in the script
enum Operation { eq, and, gt, not }
// every unresolved variable here will try to be resolved as an Operation
def propertyMissing(String property) { Operation.find { it.name() == property} }
// a class to contain what should be executed in the end of the script
#groovy.transform.ToString
class Instruction { def left; Operation operation; def right }
// a class to handle the next allowed tokens
class Expression {
Closure handler; Instruction instruction
def methodMissing(String method, args) {
println "method=$method, args=$args"
handler method, args
}
}
// a list to contain the instructions that will need to be parsed
def instructions = []
// the start of the whole mess: an integer will get this called
Integer.metaClass {
call = { Operation op ->
instruction = new Instruction(operation: op, left: delegate)
instructions << instruction
new Expression(
instruction: instruction,
handler:{ String method, args ->
instruction.right = method.toInteger()
println instructions
this
})
}
}
x = 12
y = 19
z = false
x gt 10 and y eq 20 or not z
Which will give an exception, due the not() part not being implemented, but it can build two Instruction objects before failing:
[Instruction(12, gt, 10), Instruction(19, eq, 20)]
Not sure if it is worth it.
The GDK tacks on and() and or() methods to Boolean. If you supplied a method like
Boolean not(Boolean b) {return !b}
you could write something like
(x > 10).and(y == 20).or(not(4 == 1))
I'm not sure that's particularly easy to write, though.

Resources