Scheme: using open-i/o-file function - file

I'm using MIT Scheme 10.1.5 and am curious why the following code using open-i/o-file is not working I expected. Does anyone know what the issue is?
(define l "~/tmp0")
(define x ''(a b (c d) e f))
(let ((p (open-i/o-file l)))
(begin (write x p)
(flush-output p)
(let ((r (read p)))
(close-port p)
r)))
;Value: #!eof
when I was expecting:
;Value: (quote (a b (c d) e f))
When using open-input-file or open-output-file the results are expected:
(let ((p (open-output-file l)))
(write x p)
(close-port p))
(let ((p (open-input-file l)))
(let ((r (read p)))
(close-port p)
r))
;Value: (quote (a b (c d) e f))

When you read from or write to a port, the port position is advanced. After writing to an i/o port, you need to reset the position of the port if you want to read what was written.
This does not seem to be very well documented in the MIT/GNU Scheme Reference Manual, but you can use textual-port-operation to perform manipulations on textual ports. Now, this is a bit more convoluted than you might like for a couple of reasons.
First, textual-port-operation takes a port and a symbol as its arguments and returns a procedure that accomplishes the operation, i.e., textual-port-operation does not do the operations itself.
Second, the symbol argument to textual-port-operation indicates the operation, but a complete list of these symbols is not present in the reference manual (as far as I can tell). You will need to call textual-port-operation-names on the port to find out which operations the port supports.
Here is a rewritten version of OP code that behaves as expected:
(define l "./test-file.dat")
(define x ''(a b (c d) e f))
;; (define (display-port-ops p)
;; (newline)
;; (display (textual-port-operation-names p)) (newline)
;; (newline))
(let* ((p (open-i/o-file l))
(start ((textual-port-operation p 'position) p)))
;; (display-port-ops p)
(write x p)
(flush-output p)
((textual-port-operation p 'set-position!) p start)
(let ((r (read p)))
(close-port p) r))
Here, the display-port-ops procedure was used to interrogate the port and discover which operations are supported and what symbols represent those operations. This had to be called with a port argument, so it was placed in the let* form. I called this, uncommented, before adding either of the calls to textual-port-operation so that I could see which operations were available. The position and set-position! operations looked promising, so they were incorporated into the program. Note that let* had to replace let so that the value of p could be used in an expression calculating the start position.
The call to display-port-ops, which just wraps a call to textual-port-operation-names, showed this result:
(length pathname position set-position! truename write-self close-input eof?
input-line input-open? input-channel buffered-output-bytes bytes-written
close-output output-column output-open? output-channel synchronize-output
char-set close coding known-coding? known-codings known-line-ending?
known-line-endings line-ending open? set-coding set-line-ending
supports-coding? char-ready? peek-char read-char read-substring unread-char
flush-output write-char write-substring)
Armed with these procedures, here is what happens:
Immediately after creating the port p, (textual-port-operation p 'position) is called, yielding a procedure that will return a port position; this procedure is called on the port p, and start is bound to the result, saving the initial position of the port.
After writing to the port, (textual-port-operation p 'set-position!) is called, yielding a procedure that will mutate the state of a port, setting a new position; this procedure is called on the port p and the desired position start.
Now, when read is called on p, reading commences from the port's initial position.
When the program is loaded, the test-file.dat is created as expected, and the result of reading the file back is displayed in the REPL:
1 (user) => (load "file-io.scm")
;Loading "file-io.scm"... done
;Value: (quote (a b (c d) e f))

Related

Why is this Symbolic Execution with Z3 resulting in an error?

I am trying to generate test cases using a symbolic execution logic based on the SMT Solver Z3.
I have the following code.
void foo(int a, int b, int c){
int x = 0, y = 0, z = 0;
if(a){
x = -2;
}
if (b < 5){
if (!a && c) { y = 1; }
z = 2;
}
assert(x + y + z != 3);
}
Now, an error occurs during the SMT Solving process and the resulting error log is like below.
(set-option :produce-unsat-cores true)
(set-option :produce-models true)
(set-option :produce-proofs true)
(define-sort bot () Int)
(declare-const sv_1 Int)
(declare-const sv_5 Int)
(define-fun strcmp ((a String) (b String)) Int (ite (= a b) 0 1))
(assert (! (not (= sv_1 0)) :named __a0))
(assert (! (< sv_5 5) :named __a1))
(assert (! (not (not (= sv_1 0))) :named __a2))
(assert (! (not (not (= (+ (+ (bvneg 2) 0) 2) 3))) :named __a3))
(check-sat)
(get-unsat-core)
(get-model)
I have done some testing with this code.
If I do not use x, y, z in the assert function, there is no error.
If the first 'if statement' is true (i.e. a != 0), then the program will never enter the 'if (!a && c) statement. If I erase one of these 'if statements', the there is no error. But I do not understand why this error is occurring. Could anyone explain to me why Z3 is not being able to solve this? Thank you.
You didn't tell us what exact error you're getting, so I'm assuming it comes from z3 and not from some other part of your toolchain. Let's run the SMTLib program you posted through z3. When I do that, z3
tells me that there's a "sort mismatch:"
(error "line 13 column 38: operator is applied to arguments of the wrong sort")
And this is because you've the line:
(assert (! (not (not (= (+ (+ (bvneg 2) 0) 2) 3))) :named __a3))
and in particular the expression (bvneg 2). The function bvneg is bit-vector negation, but 2 is an Integer, not a bit-vector value. You want to use regular negation instead. So, change that line to:
(assert (! (not (not (= (+ (+ (- 0 2) 0) 2) 3))) :named __a3))
With that change, z3 says:
unsat
(__a3)
(error "line 16 column 10: model is not available")
Great; so now you have unsat, and the unsat-core is __a3. The error in the last line can be ignored, it arises because you called get-model but the problem is unsatisfiable, and thus there is no model to display.
Now, you might wonder why this is unsat, perhaps you expected it to be satisfiable? You haven't told us how you converted your C function to SMTLib, and it appears that you used some unnamed tool to do so, perhaps one of your own creation. The tool clearly has a bug in it, as it created the bvneg expression that we fixed above, maybe it's not to be trusted as much! But let's see why z3 thinks this problem is unsat.
It boils down to these two lines that your tool generated:
(assert (! (not (= sv_1 0)) :named __a0))
(assert (! (not (not (= sv_1 0))) :named __a2))
Let's simplify these by dropping the annotations, and for clarity I'll rename sv_1 to a, since that seems to be the origin of the variable. This gives us:
(assert (not (= a 0)))
(assert (not (not (= a 0))))
Let's simplify a bit:
(assert (distinct a 0))
(assert (not (distinct a 0)))
(In SMTLib, (distinct x y) means (not (= x y)).)
And now we see the problem; you have two assertions the first one says a is not 0, and the second says it's not the case that a is not 0. Clearly, these two assertions conflict each other, and this is why z3 tells you unsat.
There's actually another source of conflict as well. The other assertion simplifies to:
(assert (not (not (= (+ (+ (- 0 2) 0) 2) 3)
which, if you do the arithmetic, says:
(assert (= 0 3))
which is clearly not true. (And this is why z3 tells you your unsat core is __a3; which is the root-cause of why the whole set of assumptions is unsatisfiable. Note that unsat-cores are not unique, and z3 does not guarantee it'll give you a minimal set. So it could've told you (__a0 __a2) as well as the unsat-core; but that's a separate discussion.)
So, z3 is doing the right thing given your generated SMTLib (after the correction mentioned above.)
Why your tool generates this SMTLib for the C-program is something we cannot help you with unless you tell us more about how you generated that output, or what this intermediate tool actually does. My rough guess is that it's actually generating a bunch of test cases, and eventually it comes to a point where it says "I don't have any more test cases to generate" so everything is actually fine; but there seems to be some issue with why it would generate the (get-model) call; or why it would do the bvneg call which is incorrect. But otherwise, you'll have to consult with the developers of the tool that generates this SMTLib for you for further debugging.

Multiplying numbers and outputting result in a file in SCHEME

I am new to the concept of SCHEME and just started learning Scheme (and DrRacket). Started with some online resources including, DrRacket Docs. Following this and some other references online, I am trying to solve a basic problem which involves reading 2 numbers from a file (data.inp), multiplying the numbers and displaying the output in a different file (result.out).
So far, I have been able to come up with following code,
#lang racket
(define (file->char_list path)
(call-with-input-file path
(lambda (input-port)
(let loop ((x (read-char input-port)))
(cond
((eof-object? x) '())
(#t (begin (cons x (loop (read-char input-port))))))))))
(define (yb)
;(call-with-input-file "data.inp"
;(lambda (in) (read-string 14 in)
; ))
;(call-with-output-file "result.out"
;(lambda (output-port)
; (display "(* x x)" output-port)))
; Fill in the blank
;(fprintf (current-output-port) "Done!~n"))
(string->number (apply string (file->char_list "data.inp"))))
(yb)
I am stuck at reading numbers from a file (data.inp) and multiplying them. I have references some previous stackoverflow questions but I am sort of stuck at this point. Any help will be appreciated :)
In Scheme, most of the time you'll probably want to use the default "current" ports for input and output. On most Unix systems, the default current input port is linked to stdin and the default current output port is linked to stdout.
With that in mind, reading in two numbers and writing out their product is basically:
(display (* (read) (read)))
Now, if you want to use actual input and output files, like you mentioned in your question, then you can either wrap with with-input-from-file/with-output-to-file (which temporarily changes the current input and output port):
(with-input-from-file "data.inp"
(lambda ()
(with-output-to-file "result.out"
(lambda ()
(display (* (read) (read)))))))
or you can explicitly specify ports, and leave the current/default input and output ports unchanged:
(call-with-input-file "data.inp"
(lambda (in)
(call-with-output-file "result.out"
(lambda (out)
(display (* (read in) (read in)) out)))))

Game Loop for Racket

I am working on a very basic memory game in RACKET that presents the user with 7 random numbers from 1 to 10 and asks them to type in the numbers in the same order. I can get this to work once but I want it to continually run until the user exits out. (Repeat MAIN PROGRAM) Any ideas on how to accomplish this???
(require math/base)
; =======================================
; Functions
; =======================================
; set essentially constants
(define lowerLimit 1)
(define upperLimit 11)
(define amount 7)
; builds a list with random integers between lowerLimit and upperLimit
(define (buildSimon x L)
(cond [(= x 0) L]
[else (buildSimon (- x 1) (cons (random-integer lowerLimit upperLimit) L))]))
; adds element to back of the list
(define (addBack L e)
(if (null? L)
(list e)
(cons (first L) (addBack (rest L) e))))
; gets input from user and builds list
(define (getInput n x L)
(cond [(= n 1) (addBack L x)]
[else (getInput (- n 1) (read) (addBack L x))]))
; =======================================
; Main program below here
; =======================================
; Generate new random number sequence
(printf "Simon says: ")
(define sequence (buildSimon amount (list)))
(display sequence) (newline)
(printf "== Memorize and guess ==\n")
(printf "== Type 'go' and hit enter to guess ==\n")
(read)
; Add spacing to hide numbers
(printf "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n")
(printf "== Type the numbers in order as they appeared. ==\n")
(printf "== Hit ENTER in between each number. ==\n")
; Gather input for comparison
(define answer (getInput amount (read) (list)))
; Do comparison
(if (equal? sequence answer)
(printf "Correct! Congratulations on your perfect memory.\n")
(printf "Wrong! I'm sorry your memory has failed you.\n"))
Thank you in advance.
You can create a function which contains all of your main code, with the last line of the function recursively calling itself.

Enumerating a sequence and if-then-else

To emulate a simple loop like that:
start = something;
incr = something_else;
end = yet_something_else; /* all three are numerical values, int or float */
while (start <= end) {
/* do something for its side effect, for example: */
printf("%d %d\n", start, start*start);
start += incr;
}
I could write either:
loop1(Start, End, _Incr) :-
Start > End, !. % yes, the cut is necessary!
loop1(Start, End, Incr) :-
Start =< End,
/* do something for its side effect, for example */
format('~d ~d~n', [Start, Start*Start]),
Next is Start + Incr,
loop1(Next, End, Incr).
or:
loop2(Start, End, Incr) :-
( Start =< End
-> format('~d ~d~n, [Start, Start*Start]),
Next is Start + Incr,
loop2(Next, End, Incr)
; true
).
loop/3 must (and always will be) called with all arguments instantiated to numbers.
I should be using the second version, right? The only reason there is a doubt is that the if-then-else construct is pretty much absent from introductory Prolog material, and I can't figure out why (Learn Prolog Now!, for example, otherwise a good introductory material, doesn't even mention it!). At the same time there are cuts haphazardly flying every each way.
Thanks for the help!
my preferred way, that resembles structured programming, is between/3 coupled with forall/2.
?- forall(between(1,3,N), writeln(N)).
here is an 'applicative' example, from ICLP2013 contest:
icecream(N) :-
loop(N, top(N)),
left, loop(N+1, center), nl,
loop(N+1, bottom(N)).
:- meta_predicate loop(+, 1).
loop(XH, PR) :-
H is XH,
forall(between(1, H, I), call(PR, I)).
top(N, I) :-
left, spc(N-I+1), pop,
( I > 1
-> pop,
spc(2*(I-2)),
pcl
; true
),
pcl, nl.
bottom(N, I) :-
left, spc(I-1), put(\), spc(2*(N-I+1)), put(/), nl.
center(_) :- put(/), put(\).
left :- spc(4).
pop :- put(0'().
pcl :- put(0')).
spc(Ex) :- V is Ex, forall(between(1, V, _), put(0' )).
yields
2 ?- [icecream].
% icecream compiled 0.00 sec, 10 clauses
true.
3 ?- icecream(5).
()
(())
(( ))
(( ))
(( ))
/\/\/\/\/\/\
\ /
\ /
\ /
\ /
\ /
\/
true.
I don't know why they don't mention it. All practical programmers use it.
But we can avoid using of cut/if-then-else if rewrite your code with a failure-driven loop.
loop(From, To, Incr, Val) :-
From =< To,
( Val = From
; Next is From + Incr,
loop(Next, To, Incr, Val)
).
print_squares(Start, End, Incr) :-
loop(Start, End, Incr, Val),
Square is Val * Val,
format('~d ~d~n', [Val, Square]),
fail
;
true.
In a case Incr = 1 you can use between/3 from the standard library:
print_squares(Start, End) :-
between(Start, End, Val),
Square is Val * Val,
format('~d ~d~n', [Val, Square]),
fail
;
true.
If you know Russian or can translate it I can recommend my book http://sourceforge.net/projects/uranium-test/files/prolog/speed_prolog.pdf/download as an introductory matherial for Prolog.
Probably a better way to enumerate a sequence of (float) numbers:
sequence(First, Step, Last, R) :-
D is Last - First,
sign(Step) =:= sign(D),
N is floor(D / Step),
between(0, N, X),
R is First + X * Step.
One of the virtues of this solution is that it does not accumulate a floating point error like Next is This + Step.

how to skip a portion while debugging a recursive function with gdb

Here is a function in my program
void
quicksort (int *num, int p, int r, int june)
{
int q, bbc, ccd;
if (p < r)
{
call++;
q = partition (num, p, r, june);//<--I want to skip this call in gdb session
bbc = q - 1 - p + 1;//<-- and want to continue execution step by step from here
quicksort (num, p, q - 1, bbc);
ccd=r-q+1;
quicksort (num, q + 1, r, ccd);
}
} //since it is a recursive function each time quicksort is called partition is also executed I want to focus my debugging only to quicksort
If you notice it calls another function partition in between.While running in a gdb session
I want to skip the gdb showing me steps of parition i.e. I know function partition is correct so do what partition does and then jump to next instruction
bbc = q - 1 - p + 1;
and in my debugging session do not show info about partition.
So how can I skip that part and continue debugging quicksort.
I think you are looking for a step over.
Step Over is the same as Step Into,
except that when it reaches a call for
another procedure, it will not step
into the procedure. The procedure will
run, and you will be brought to the
next statement in the current
procedure.
Quote from http://www.developerfusion.com/article/33/debugging/4/
In GDB, you do this by issuing the next command.
When you are running the q = partition (num, p, r, june); line in gdb, type next and it will just execute the partition function without going into its code in detail.
You can find detailed information about stepping in gdb in this reference.
b <line number>
will set a break point
c
will continue until the next breakpoint.
You can either set a breakpoint for the line after partition:
b <line number>
Then use c to continue until the breakpoint.
Or you can use n to skip over the partition call (that is, type n when you reach the partition call, and it will skip the body of the function).
Or you can type finish to exit the partition function after entering it.

Resources