Minizinc nested output loop - minizinc

I am trying to write an output statement with nested loops, and non-trivial output at the outer levels. If Minizinc had a top level for command, I would do something like
for (f in Foo) (
output(["Foo: ", f])
for (b in Bar) (
for (q in Quz) (
output([myArray[f,b,q], " "]);
)
output(["\n"]);
)
output(["\n"]);
)
so that if
myArray = [[[1,2], [3,4]], [[5,6], [7,8]]];
it would output
Foo: 1
1 2
3 4
Foo: 2
5 6
7 8
I think I can do this with something like
output(if (b = 1 /\ q = 1) then "Foo: " ++ show(f) else "" endif ++
show(myArray[f,b,q] ++ " " ++
if (<maximum q>) <newline> ++
if (<maximum q and maximum b>) <newline>
| f in Foo, b in Bar, q in Quz);
but that seems awkward (and my first attempt did not work).
I saw Minizinc nested for loop which is different, because all of the output is inside the inner-most loop. I want output in the outer loops as well.
I think a slightly clearer version of the accepted answer would be
output [
"Foo: \(f)\n"
++ concat(
concat([show(myArray[f,b,q]) ++ " " | q in Quz])
++ "\n"
| b in Bar])
++ "\n"
| f in Foo];
This avoids the if/then/else construct, and makes it clear that we are adding additional output before/after each inner loop.

As you already said: MiniZinc output statements can be a little awkward. The output statement consists of the keyword output followed by an array of strings. In a lot of cases we would like to use for-loop, but in a declarative language like MiniZinc those kind of control-flow structure are not available.
You already offered the solution though: Array Comprehensions! It seems you were almost there, but your syntax was a little off and you might not be understanding how they actually work. An array comprehension is similar to a for-loop in that it does iterate over all values in a set. However, it is different in that it doesn't just execute the statements in the loop, but evaluates them and all results need to be of the same type, string in this case.
The output statement you are writing could be written like this:
output [
"Foo: \(f)\n"
++ concat(["\(myArray[f,b,q])"
++ if q == max(Quz
then "\n"
else " "
endif
|b in Bar, q in Quz])
++ "\n"
| f in Foo];

Related

Functional Way of handling corner case in Folds

I've a list of nodes (String) that I want to convert into something the following.
create X ({name:"A"}),({name:"B"}),({name:"B"}),({name:"C"}),({name:"D"}),({name:"F"})
Using a fold I get everything with an extra "," at the end. I can remove that using a substring on the final String. I was wondering if there is a better/more functional way of doing this in Scala ?
val nodes = List("A", "B", "B", "C", "D", "F")
val str = nodes.map( x => "({name:\"" + x + "\"}),").foldLeft("create X ")( (acc, curr) => acc + curr )
println(str)
//create X ({name:"A"}),({name:"B"}),({name:"B"}),({name:"C"}),({name:"D"}),({name:"F"}),
Solution 1
You could use the mkString function, which won't append the seperator at the end.
In this case you first map each element to the corresponding String and then use mkString for putting the ',' inbetween.
Since the "create X" is static in the beginning you could just prepend it to the result.
val str = "create X " + nodes.map("({name:\"" + _ + "\"})").mkString(",")
Solution 2
Another way to see this: Since you append exactly one ',' too much, you could just remove it.
val str = nodes.foldLeft("create X ")((acc, x) => acc + "({name:\"" + x + "\"}),").init
init just takes all elements from a collection, except the last.
(A string is seen as a collection of chars here)
So in a case where there are elements in your nodes, you would remove a ','. When there is none you only get "create X " and therefore remove the white-space, which might not be needed anyways.
Solution 1 and 2 are not equivalent when nodes is empty. Solution 1 would keep the white-space.
Joining a bunch of things, splicing something "in between" each of the things, isn't a map-shaped problem. So adding the comma in the map call doesn't really "fit".
I generally do this sort of thing by inserting the comma before each item during the fold; the fold can test whether the accumulator is "empty" and not insert a comma.
For this particular case (string joining) it's so common that there's already a library function for it: mkString.
Move "," from map(which applies to all) to fold/reduce
val str = "create X " + nodes.map( x => "({name:\"" + x + "\"})").reduceLeftOption( _ +","+ _ ).getOrElse("")

simple function to return list of integers

if am trying to write a simple function that list of pair of integers - representing a graph and returns a list of integers : all the nodes in a graph
eg if input is [(1,2) (3,4) (5,6) (1,5)]
o/p should be [1,2,3,4,5,6,1,5]
The function is simply returning list of nodes , in the returning list values may repeat as above.
I wrote the following function
fun listofnodes ((x:int,y:int)::xs) = if xs=nil then [x::y] else [[x::y]#listofnodes(xs)]
stdIn:15.12-15.18 Error: operator and operand don't agree [tycon mismatch
operator domain: int * int list
operand: int * int
in expression:
x :: y.
I am not able to figure out what is wrong.
first of all you should know what each operator does:
:: puts individual elemtents into an existing list so that: 1::2::3::[] = [1,2,3]
# puts two lists together so that: [1,2] # [3,4] = [1,2,3,4]
you can also use :: to put lists together but then it becomes a list of lists like:
[1,2] :: [3,4] = [[1,2],[3,4]]
so by writing [x::y] you are saying that x and y should become a list inside a list.
and you shouldnt use an if statement to check for the end of the list, instead you can use patterns to do it like this:
fun listofnodes [] = []
| listofnodes ((x,y)::xs) = x :: y :: listofnodes(xs);
the first pattern assures that when we reach the end of the list, when you extract the final tuple your xs is bound to an empty list which it calls itself with, it leaves an empty list to put all the elements into, so that [(1,2) (3,4) (5,6) (1,5)] would evaluate like this:
1 :: 2 :: 3 :: 4 :: 5 :: 6 :: 1 :: 5 :: [] = [1,2,3,4,5,6,1,5].
you could also make it like this:
fun listofnodes [] = []
| listofnodes ((x,y)::xs) = [x,y] # listofnodes(xs);
this way you make a small 2 element list out of each tuple, and then merge all these small lists into one big list. you dont really need the empty list at the end, but its the only way of ensuring that the recursion stops at the end of the list and you have to put something on the other side of the equals sign. it evaluates like this:
[1,2] # [3,4] # [5,6] # [1,5] # [] = [1,2,3,4,5,6,1,5].
also you cast your x and y as ints, but you dont really have to. if you dont, it gets the types " ('a * 'a) list -> 'a list " which just means that it works for all input types including ints (as long as the tuple doesnt contain conflicting types, like a char and an int).
im guessing you know this, but in case you dont: what you call pairs, (1,2), is called tuples.

Scala equivalent of Haskell's do-notation (yet again)

I know that Haskell's
do
x <- [1, 2, 3]
y <- [7, 8, 9]
let z = (x + y)
return z
can be expressed in Scala as
for {
x <- List(1, 2, 3)
y <- List(7, 8, 9)
z = x + y
} yield z
But, especially with monads, Haskell often has statements inside the do block that don't correspond to either <- or =. For example, here's some code from Pandoc that uses Parsec to parse something from a string.
-- | Parse contents of 'str' using 'parser' and return result.
parseFromString :: GenParser tok st a -> [tok] -> GenParser tok st a
parseFromString parser str = do
oldPos <- getPosition
oldInput <- getInput
setInput str
result <- parser
setInput oldInput
setPosition oldPos
return result
As you can see, it saves the position and input, runs the parser on the string, and then restores the input and position before returning the result.
I can't for the life of me figure out how to translate setInput str, setInput oldInput, and setPosition oldPos into Scala. I think it would work if I just put nonsense variables in so I could use <-, like
for {
oldPos <- getPosition
oldInput <- getInput
whyAmIHere <- setInput str
result <- parser
...
} yield result
but I'm not sure that's the case and, if it is correct, I'm sure that there must be a better way to do this.
Oh, and if you can answer this question, can you answer one more: how long do I have to stare at Monads before they don't feel like black magic? :-)
Thanks!
Todd
Yes, that translation is valid.
do { x <- m; n } is equivalent to m >>= \x -> n, and do { m; n } is equivalent to m >> n. Since m >> n is defined as m >>= \_ -> n (where _ means "don't bind this value to anything"), that is indeed a valid translation; do { m; n } is the same as do { _ <- m; n }, or do { unusedVariable <- m; n }.
A statement without a variable binding in a do block simply disregards the result, usually because there's no meaningful result to speak of. For instance, there's nothing interesting to do with the result of putStrLn "Hello, world!", so you wouldn't bind its result to a variable.
(As for monads being black magic, the best realisation you can have is that they're not really complicated at all; trying to find deeper meaning in them is not generally a productive way of learning how they work. They're simply an interface to compose computations that happen to be particularly common. I recommend reading the Typeclassopedia to get a solid grasp on Haskell's abstract typeclasses, though you'll need to have read a general Haskell introduction to get much out of it.)

how to approach implementing TCO'ed recursion

I have been looking into recursion and TCO. It seems that TCO can make the code verbose and also impact the performance. e.g. I have implemented the code which takes in 7 digit phone number and gives back all possible permutation of words e.g. 464-7328 can be "GMGPDAS ... IMGREAT ... IOIRFCU" Here is the code.
/*Generate the alphabet table*/
val alphabet = (for (ch <- 'a' to 'z') yield ch.toString).toList
/*Given the number, return the possible alphabet List of String(Instead of Char for convenience)*/
def getChars(num : Int) : List[String] = {
if (num > 1) return List[String](alphabet((num - 2) * 3), alphabet((num - 2) * 3 + 1), alphabet((num - 2) * 3 + 2))
List[String](num.toString)
}
/*Recursion without TCO*/
def getTelWords(input : List[Int]) : List[String] = {
if (input.length == 1) return getChars(input.head)
getChars(input.head).foldLeft(List[String]()) {
(l, ch) => getTelWords(input.tail).foldLeft(List[String]()) { (ll, x) => ch + x :: ll } ++ l
}
}
It is short and I don't have to spend too much time on this. However when I try to do that in tail call recursion to get it TCO'ed. I have to spend a considerable amount of time and The code become very verbose. I won't be posing the whole code to save space. Here is a link to git repo link. It is for sure that quite a lot of you can write better and concise tail recursive code than mine. I still believe that in general TCO is more verbose (e.g. Factorial and Fibonacci tail call recursion has extra parameter, accumulator.) Yet, TCO is needed to prevent the stack overflow. I would like to know how you would approach TCO and recursion. The Scheme implementation of Akermann with TCO in this thread epitomize my problem statement.
Is it possible that you're using the term "tail call optimization", when in fact you really either mean writing a function in iterative recursive style, or continuation passing style, so that all the recursive calls are tail calls?
Implementing TCO is the job of a language implementer; one paper that talks about how it can be done efficiently is the classic Lambda: the Ultimate GOTO paper.
Tail call optimization is something that your language's evaluator will do for you. Your question, on the other hand, sounds like you are asking how to express functions in a particular style so that the program's shape allows your evaluator to perform tail call optimization.
As sclv mentioned in the comments, tail recursion is pointless for this example in Haskell. A simple implementation of your problem can be written succinctly and efficiently using the list monad.
import Data.Char
getChars n | n > 1 = [chr (ord 'a' + 3*(n-2)+i) | i <- [0..2]]
| otherwise = ""
getTelNum = mapM getChars
As said by others, I would not be worried about tail call for this case, as it does not recurse very deeply (length of the input) compared to the size of the output. You should be out of memory (or patience) before you are out of stack
I would implement probably implement with something like
def getTelWords(input: List[Int]): List[String] = input match {
case Nil => List("")
case x :: xs => {
val heads = getChars(x)
val tails = getTelWords(xs)
for(c <- heads; cs <- tails) yield c + cs
}
}
If you insist on a tail recursive one, that might be based on
def helper(reversedPrefixes: List[String], input: List[Int]): List[String]
= input match {
case Nil => reversedPrefixes.map(_.reverse)
case (x :: xs) => helper(
for(c <- getChars(x); rp <- reversedPrefixes) yield c + rp,
xs)
}
(the actual routine should call helper(List(""), input))

How to operate on part of line only

How do I make sed operate on specific parts of a line only? And, on the contrary, how do I make sed not work on specific parts of a line?
Examples:
"A a A a ( A a ) A ( a A ) a"
How do I, for instance, replace all the As with Ts only between the ( and ) to obtain:
"A a A a ( T a ) A ( a T ) a"
And given next example input:
"F f F f ( F f ) F ( f F ) f"
How do I, for instance, replace all the Fs with Xs but not between the ( and ) to
obtain:
"X f X f ( F f ) X ( f F ) f"
I searched Google but found nothing usable. I guess it's a general question about sed. The problem is reducible to general sed "templates", I hope.
having FROM and TO then operate between them only (on all occurrences on given line)
having FROM and TO operate anywhere else than between them...
special case when FROM and TO are the same (between " and " or "FOO" and "FOO" etc.)
for both 1. and 2.
It should work with any operation, not just substitution, but also with printing etc., like printing everything between strings "FOO" and "BAR" in string.
"1 2 3 BAR a b c FOO d e f BAR g a h FOO i j k BAR l m n FOO o p q"
The result will be
" d e f i j k "
So, general examples on how to do it would be highly appreciated. It also seems that this question is quite common, but no good howto is found on the Google yet. I also guess this
would be quite challenging to answer. Please, also do no give any hints on how to do it
using Perl, AWK or whatever else than sed. This question is really a sed-only question.
Divide and conquer.
Insert newlines to separate the segments then use the newlines, line beginning (^), line ending ($) and delimiter characters (parentheses in this case) as anchors and loop. The added newlines are removed at the end.
$ echo "A a A a ( A a ) A ( a A ) a" |
sed 's/([^)]*)/\n&/g;
:a;
s/\(\n([^)]*\)A\([^)]*)\)/\1T\2/;
ta;
s/\n//g'
A a A a ( T a ) A ( a T ) a
$ echo "F f F f ( F f ) F ( f F ) f" |
sed 's/(/\n(/g;
s/)/)\n/g;
:a;
s/\([^(]*\)F\([^)]*\(\n\|$\)\)/\1X\2/g;
ta;
s/\n//g'
X f X f ( F f ) X ( f F ) f
$ echo "1 2 3 BAR a b c FOO d e f BAR g a h FOO i j k BAR l m n FOO o p q" |
sed 's/^/BAR/;
s/$/FOO/;
s/FOO/&\n/g;
s/BAR/\n&/g;
s/BAR[^\n]*\n//g;
s/[^\n]*FOO\n//g;
s/\n//g'
d e f i j k
This might work for you (GNU sed):
sed ':a;s/\(([^)]*\)A/\1T/;ta' file # for case 1
sed ':a;s/\(([^)]*\)F/\1\n/;ta;y/F\n/TF/' file # for case 2
For case 1 use a loop to substitute A's inside brackets to T's.
For case 2 use the same as above to change F's inside brackets to newlines, then translate F's and newlines to X's and F's respectively.
Case 3 is a little more involved but can be done in 2 substitute commands:
sed -r 's/FOO|BAR/\n&/g;s/[^\n]*(\nBAR[^\n]*)*(\nFOO([^\n]*)\nBAR)?(\nFOO[^\n]*$)?/\3/g' file
First prefix each FOO and BAR strings with newlines. Then look for all combinations of FOO and BAR and only keep the strings between FOO and BAR. The newlines allow the use of the negative class to simplify the procedure.