I am trying to establish a menu so the program can change based on user input. This seems to work but I wanted to see if it was the "RIGHT" way of doing it. Also when the program runs after I input a number I get a (void) displayed. How can I make the (void) go away. Any help would be appreciated....thank you.
(printf "Choose your difficulty\n")
(printf "1. Easy\n")
(printf "2. Medium\n")
(printf "3. Hard\n")
(printf "4. Insane\n")
(define choice (read))
(define (choose c)
(cond [(= c 1)(set! amount 3)]
[(= c 2)(set! amount 7)]
[(= c 3)(set! amount 10)]
[(= c 4)(set! amount 99)]
[else (printf "Invalid choice.\n")]))
(choose choice)
Generally, you should avoid using set!. The functional way to implement this might look like this:
(define (choose c)
(cond [(= c 1) 3]
[(= c 2) 7]
[(= c 3) 10]
[(= c 4) 99]
[else (printf "Invalid choice.\n") (choose (read))]))
(define amount (choose (read)))
Due to the (choose (read)) inside the else clause, the program will ask until it gets a valid input, which is usually what you want. If it isn't, you'll want to figure out a reasonable value for amount to have (e.g. a suitable default).
Related
I am very new to working with Racket. I need my interpreter to correctly identify the following statement and execute the "while" loop.
(= x 10)
(while (> x 0) ((print x)(= x (- x 1))))))
Currently, my implementation of a while loop is throwing an error I don't entirely understand.
My partial implementation is as follows:
(define interp
(lambda (stmt myEnv)
(cond
((eqv? (car stmt) 'print) (begin
(display "\n")
(display (exp myEnv (cadr stmt)))
myEnv))
((eqv? (car stmt) '=) (extend-env myEnv (cadr stmt)(exp myEnv (caddr stmt))))
((eqv? (car stmt) 'while) (while myEnv (cadr stmt)))
(define (while cond body)
(when (cond)
(display "x")
(while cond body)))
I'm getting an error that says:
application: not a procedure;
expected a procedure that can be applied to arguments
given: '(extend-env x 10 (empty-env))
Which leads me to believe I am fatally misunderstanding a key component of how Racket processes functions. Could someone explain what my misstep may be, and how I could go about fixing this definition? A large portion of this skeleton code has been provided for me, so if possible I would like to get the while definition working without modifying anything other than the while definition and the line where I am passing the variables and calling the while definition.
In python objects, overriding the methods __repr__ and __str__ of an object allows one to provide "unambiguous" and "human-readable" representations of the object, respectively. How does one achieve similar behavior in Racket?
I came across the printable<%> interface here, which seems like it should be usable for this purpose, but I haven't been able to get it to work quite as I expect it to. Building on the standard "fish" example from the docs:
(define fish%
(class* object% (printable<%>)
(init size) ; initialization argument
(super-new) ; superclass initialization
;; Field
(define current-size size)
;; Public methods
(define/public (get-size)
current-size)
(define/public (grow amt)
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))
;; implement printable interface
(define/public (custom-print port quoting-depth)
(print "Print called!"))
(define/public (custom-write port)
(print "Write called!"))
(define/public (custom-display port)
(print "Display called!"))))
This is the output I get:
> (define f (new fish% [size 10]))
> f
"Display called!""Display called!""Print called!"
> (print f)
"Write called!""Print called!"
> (display f)
"Display called!""Display called!"
> (write f)
"Write called!""Write called!"
>
So the question is threefold:
Why does it behave this way, i.e. with the multiple methods being invoked on an apparently singular rendering of the object?
What should the methods custom-print, custom-write, and custom-display evaluate to? Should they simply return a string, or should they actually entail the side effect of printing, writing, or displaying, as the case may be? E.g. should the custom-write method invoke the write function internally?
Is this the right construct to use for this purpose at all? If not, is there one / what is it?
As for
Why does it behave this way, i.e. with the multiple methods being invoked on an apparently singular rendering of the object?
You have accidently used print in write, so writing the value, will first print the value.
(define/public (custom-write port)
(print "Write called!"))
A similar problem is present in display.
Also remember to print/write/display to the proper port.
Try
#lang racket
(define fish%
(class* object% (printable<%>)
(init size) ; initialization argument
(super-new) ; superclass initialization
;; Field
(define current-size size)
;; Public methods
(define/public (get-size)
current-size)
(define/public (grow amt)
(set! current-size (+ amt current-size)))
(define/public (eat other-fish)
(grow (send other-fish get-size)))
;; implement printable interface
(define/public (custom-print port quoting-depth)
(print (~a "Print " current-size "\n") port))
(define/public (custom-write port)
(write (~a "Write " current-size "\n") port))
(define/public (custom-display port)
(display (~a "Display " current-size "\n") port))))
In the repl you will see:
> (define f (new fish% [size 10]))
> f
"Print 10\n"
> (display f)
Display 10
> (write f)
"Write 10\n"
Another answer has already helped you find the problem in your code—you need to use the port given as an argument, not the implicit (current-output-port)—but the explanation isn't quite right. To tackle your questions in reverse order:
Is this the right construct to use for this purpose at all? If not, is there one / what is it?
Yes, printable<%> is the right construct to use to customize printing of a class-based object. More generally, a struct type that is not a class can customize printing for instance through the gen:custom-write generic interface or the low-level prop:custom-write struct type property, which is used to implement printable<%>.
What should the methods custom-print, custom-write, and custom-display evaluate to? Should they simply return a string, or should they actually entail the side effect of printing, writing, or displaying, as the case may be? E.g. should the custom-write method invoke the write function internally?
The methods should actually do the side-effect of performing IO on the port they are given as an argument. They should use the corresponding function (e.g. write for custom-write, print for custom-print) internally for recursively printing/writing/displaying values in fields. On the other hand, when directly emitting particular characters, they should generally use functions like write-char, write-string, or printf. The docs for gen:custom-write give an example of a tuple datatype that prints as <1, 2, "a">: it uses write-string for the angle-brackets and commas, but recursive print/write/display for the elements of the tuple.
Why does it behave this way, i.e. with the multiple methods being invoked on an apparently singular rendering of the object?
This is the most involved part of your question. Printing in Racket is customizable through several hooks: for a few examples, see current-print, port-write-handler, global-port-print-handler, and make-tentative-pretty-print-output-port. Many of these customization hooks use intermediate ports in the process of producing output.
One thing that is not a part of the explanation is the fact that you used print in your implementation, particularly as print is bound to the normal Racket function by lexical scope, not to a method of your object.
As an illustration, consider the following adaptation of your example, which reports to the (current-output-port) the identity of the port given as an argument to the method:
#lang racket
(define report
(let ([next-id 0]
[id-cache (make-hash)])
(λ (op port)
(printf "~a ~a ~v\n"
op
(hash-ref id-cache
port
(λ ()
(define id next-id)
(hash-set! id-cache port id)
(set! next-id (add1 next-id))
id))
port))))
(define fish%
(class* object% (printable<%>)
(super-new)
;; implement printable interface
(define/public (custom-print port quoting-depth)
(report "custom-print " port))
(define/public (custom-write port)
(report "custom-write " port))
(define/public (custom-display port)
(report "custom-display" port))))
(define f (new fish%))
f
(print f)
(newline)
(display f)
(newline)
(write f)
In DrRacket, this generates the output:
custom-display 0 #<output-port:null>
custom-display 1 #<output-port:null>
custom-print 2 #<printing-port>
custom-display 3 #<output-port:null>
custom-display 4 #<output-port:null>
custom-print 5 #<printing-port>
custom-display 6 #<output-port:null>
custom-display 7 #<printing-port>
custom-display 8 #<output-port:null>
custom-write 9 #<printing-port>
while at the command line, the output is:
$ racket demo.rkt
custom-write 0 #<output-port:null>
custom-print 1 #<output-port:redirect>
custom-write 2 #<output-port:null>
custom-print 3 #<output-port:redirect>
custom-display 4 #<output-port:null>
custom-display 5 #<output-port:redirect>
custom-write 6 #<output-port:null>
custom-write 7 #<output-port:redirect>
Consider the following inductive definition describing the small step semantics of the language of guarded commands:
inductive small_step :: "com × state ⇒ com × state ⇒ bool" (infix "→" 55)
where
Assign: "(x ::= a, s) → (SKIP, s(x := aval a s))" |
Seq1: "(SKIP;;c2,s) → (c2,s)" |
Seq2: "(c1,s) → (c1',s') ⟹ (c1;;c2,s) → (c1';;c2,s')" |
IfBlock: "(b,c) ∈ set gcs ⟹ bval b s ⟹ (IF gcs FI,s) → (c,s)" |
DoTrue: "(b,c) ∈ set gcs ⟹ bval b s ⟹ (DO gcs OD,s) → (c;;DO gcs OD,s)" |
DoFalse: "(∀ b c. (b,c) ∈ set gcs ⟶ ¬ bval b s) ⟹ (DO gcs OD,s) → (SKIP,s)"
I want to prove:
lemma "((c1 ;; c2) ;; c3) ~ (c1 ;; (c2 ;; c3))"
where:
definition equiv_c :: "com ⇒ com ⇒ bool" (infix "~" 50) where
"c ~ c' ≡ ∀ s c0 s0. (c,s) → (c0,s0) = (c',s) → (c0,s0)"
And it is getting surprinsingly difficult to do so. The closest solution I have found is given in "An operational semantics for the Guarded Command Language" by Johan J. Lukkien. However, in that article programs are modelled as sequences of states whereas here I'm modelling them as command configurations, plus states. Perhaps, there is a relation between the two but my tries so far have been frustrated.
Do you see a way to prove this lemma in Isabelle?
The desired lemma as stated does not hold. So you will not be able to prove this. I can see two main problems:
The → denotes one step of the execution, but equivalence should talk about the whole behaviour, not just one step. After one step, it is likely that the resulting programs are still different.
The semantics can get stuck for some programs, e.g., IF [] FI. Such stuck states make it hard to state equivalence if you want to say something about the remaining program c0. For example, take c1 = SKIP;; IF [] FI in your lemma and c2 = c3 = SKIP. Then no partially evaluated command reachable from (c1 ;; c2) ;; c3 is identical to one reachable from c1 ;; (c2 ;; c3).
I recommend that you first figure out what the behaviour of a program is supposed to be. For a while language, this is typically the set of reachable final states and possibly non-termination. Then, you have to decide what kind of equivalence you are interested in. Typically, one looks at trace equivalence or at bisimulation, which are not the same for non-deterministic programs. And the equivalence notion will determine how to prove such a lemma.
No breakpoint can be set on line 5, which contains [x].
IntelliJ won't let me do so. I used different plugin, such as La Clojure and Cursive. Both stop at line 3 rather than line 5.
So, how people step into the code in Clojure?
Is there any syntax suggestion or maybe tool to help with?
(defn flattenlist
([x & more]
(concat (if (vector? x)
(apply flattenlist x)
[x]
)
(if (= more nil)
nil
(apply flattenlist more))))
)
(flattenlist [[1 [[2]]] 3 [4 5] 6])
First, by convention, all trailing parentheses are on the same line, something like this:
(defn flattenlist
([x & more]
(println x)
(concat (if (vector? x)
(apply flattenlist x)
[x])
(if (= more nil)
nil
(apply flattenlist more)))))
(flattenlist [[1 [[2]]] 3 [4 5] 6])
Secondly, when you use composable functions, it is easy to insert a println and run/test just that function because it is referentially transparent. I am only a Clojure hobbyist, but I typically debug with printlns and unit tests. Using breakpoints isn't really that reliable.
If you really want something similar to setting a breakpoint, you can try using this debugging macro (not mine).
Basically, I need to write a what the title says, the only relationship I have been able to think of is if I take some number of elements from a list with TAKE and then take the not-as-important other half with CDR and then APPEND the two that I took to prove that it's the same as the original list.
(After long painful hours of building it), the proof seems to be fine (It compiles just fine), but for some reason it fails when run.
I am using Proofpad with Dracula, in case you need the information.
Here is the code:
(include-book "doublecheck" :dir :teachpacks)
(defproperty take-append-relationship-test ;not sure why this fails.
(xs :value (random-integer-list))
(iff (consp xs)
(let* ((x1 (take 1 xs))
(xs2 (cdr xs)))
(equal (append x1 xs2)
xs))))
Here is the error log I get.
By the simple :definition TAKE we reduce the conjecture to
Goal'
(COND ((CONSP XS)
(LET ((X1 (FIRST-N-AC 1 XS NIL)))
(EQUAL (APPEND X1 (CDR XS)) XS)))
((LET ((X1 (FIRST-N-AC 1 XS NIL)))
(EQUAL (APPEND X1 (CDR XS)) XS))
NIL)
(T T)).
This simplifies, using the :definition FIRST-N-AC, the :executable-
counterparts of BINARY-+, BINARY-APPEND, CONS, FIRST-N-AC and ZP, primitive
type reasoning and the :rewrite rules DEFAULT-CAR and DEFAULT-CDR,
to
Goal''
(IMPLIES (CONSP XS)
(EQUAL (APPEND (FIRST-N-AC 1 XS NIL) (CDR XS))
XS)).
The destructor terms (CAR XS) and (CDR XS) can be eliminated by using
CAR-CDR-ELIM to replace XS by (CONS XS1 XS2), (CAR XS) by XS1 and (CDR XS)
by XS2. This produces the following goal.
Goal'''
(IMPLIES (CONSP (CONS XS1 XS2))
(EQUAL (APPEND (FIRST-N-AC 1 (CONS XS1 XS2) NIL)
XS2)
(CONS XS1 XS2))).
This simplifies, using primitive type reasoning, to
Goal'4'
(EQUAL (APPEND (FIRST-N-AC 1 (CONS XS1 XS2) NIL)
XS2)
(CONS XS1 XS2)).
Normally we would attempt to prove Goal'4' by induction. However,
we prefer in this instance to focus on the original input conjecture
rather than this simplified special case. We therefore abandon our
previous work on this conjecture and reassign the name *1 to the original
conjecture. (See :DOC otf-flg.)
No induction schemes are suggested by *1. Consequently, the proof
attempt has failed.
Summary
Form: ( DEFTHM TAKE-APPEND-RELATIONSHIP-TEST ...)
Rules: ((:DEFINITION FIRST-N-AC)
(:DEFINITION IFF)
(:DEFINITION TAKE)
(:ELIM CAR-CDR-ELIM)
(:EXECUTABLE-COUNTERPART BINARY-+)
(:EXECUTABLE-COUNTERPART BINARY-APPEND)
(:EXECUTABLE-COUNTERPART CONS)
(:EXECUTABLE-COUNTERPART FIRST-N-AC)
(:EXECUTABLE-COUNTERPART ZP)
(:FAKE-RUNE-FOR-TYPE-SET NIL)
(:REWRITE DEFAULT-CAR)
(:REWRITE DEFAULT-CDR))
Time: 0.00 seconds (prove: 0.00, print: 0.00, other: 0.00)
Prover steps counted: 328
---
The key checkpoint goal, below, may help you to debug this failure.
See :DOC failure and see :DOC set-checkpoint-summary-limit.
---
*** Key checkpoint before reverting to proof by induction: ***
Goal''
(IMPLIES (CONSP XS)
(EQUAL (APPEND (FIRST-N-AC 1 XS NIL) (CDR XS))
XS))
ACL2 Error in ( DEFTHM TAKE-APPEND-RELATIONSHIP-TEST ...): See :DOC
failure.
******** FAILED ********
Could someone at least point me in the right direction?
I have read the error log and what I get is that there is some sort of redundancy.
I am not sure how to fix this at all.
If I do that (so like '(1 2 3 4) instead of (random-integer-list)), it throws an error:
ACL2 Error in TOP-LEVEL: One value, '(1 2 3 4 5), is being returned
where 2 values were expected. Note: This error occurred in the context
(MV-LET (XS STATE)
'(1 2 3 4 5)
(IF T
(MV-LET (STATE RESULT ASSIGNMENTS)
(EXPAND-VARS NIL (IFF # #))
(MV STATE RESULT (CONS # ASSIGNMENTS)))
(MV STATE 'WHERE-NOT-MATCHED NIL))).
(See :DOC set-iprint to be able to see elided values in this message.)
My setup:
Install Racket
Open it and run the following code:
(pound)lang racket
(require (planet cce/dracula:8:23/lang/dracula))
Restart Dr Racket. Click the "Choose Language" at the bottom of the window and choose ACL2 under Dracula.
From the Dracula menu, choose "Change ACL2 Executable Path..." and choose "run_acl2" (or "run_acl2.exe") which is located in the installation folder of proofpad (i.e. "C:\Program Files (x86)\Proof Pad", if you have a 64 bits PC)
download PSP++ and run it. Make sure to unzip it in the Proofpad installation directory, otherwise it will tell you it didn't find the things it needed.