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>
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).
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).
I can connect manually by doing:
M-x sql-postgres
and type the User, Database, Host, Server
I'd like to do something like:
(connect-foo (user "me")(database "bar")(host "earth"))
Solution so far:
I grabbed some code from sql.el and changed it so I can use it non-interactively.
(defun sql-create-buffer (profile)
"derived from sql-product-interactive in sql.el which is"
"covered by GNU General Public License version 3."
(setq sql-user (cdr (assoc 'user profile))
sql-password (cdr (assoc 'password profile))
sql-server (cdr (assoc 'server profile))
sql-database (cdr (assoc 'database profile)))
(setq product 'postgres) ;;(cdr (assoc 'product profile)))
(when (sql-product-feature :sqli-connect product)
(if (comint-check-proc "*SQL*")
(pop-to-buffer "*SQL*")
;; Connect to database.
(message "Login...")
(funcall (sql-product-feature :sqli-connect product))
;; Set SQLi mode.
(setq sql-interactive-product product)
(setq sql-buffer (current-buffer))
(sql-interactive-mode)
;; All done.
(message "Login...done")
(pop-to-buffer sql-buffer))))
(setq bar-profile '(
(product . "postgres")
(user . "me")
(password . "")
(server . "earth")
(database . "bar")))
I don't know what to do with the 'product' parameter, so I left it hard coded for now.
It is 'postgres in sql.el.
(sql-create-buffer bar-profile)
It seems that package is not intended to be used non-interactively (probably to discourage writing login info into init files, which is a perfectly sound principle).
However, if you really want to avoid answering the questions, you can simply redefine the query function, like this:
(defun sql-get-login (&rest what)
(setq sql-user "me"
sql-password "secret"
sql-server "localhost"
sql-database "MyDB"))