I have a serial port input in Racket, and I want to only read the new incoming data when I check it. In Python, I can easily do this with my_serial_port.flush() before reading. However, I can't figure out how to do something analogous in Racket. When I just read from the port with (read-bytes 1 in-port)), I'm getting "old" data that I want to flush out before reading.
There is a flush-output function, but I can't find anything analogous for flushing the input buffer. I've tried a variety of things on that page, but nothing seems to achieve this functionality. It seems like this should be pretty straightforward, so I feel like I must be missing something.
We're talking about two slightly different uses of the word ``flush.'' In the case of the output buffers, flushing ensures that buffered data is actually sent to the port. In your case, you're talking about discarding input data.
This is probably the right way to do what you want (the code includes an example input port to show how it works)
#lang racket
(define buf-size 20000)
;; given a port, allocate a buffer of size 'buf-size' and
;; repeatedly read available bytes or specials until 0
;; bytes are available.
(define (drain-port port)
(define buf (make-bytes buf-size))
(let loop ()
(define try-read (read-bytes-avail!* buf port))
(cond [(or (eof-object? try-read)
(and (number? try-read) (= try-read 0)))
'done]
[else
(loop)])))
(define example-port (open-input-string "abcdef"))
(drain-port example-port)
Related
Is it possible to define a procedure f such that it prints Exiting... if it is the last thing to do before exiting, and prints Not done yet... otherwise?
For examples,
(display "hello, world\n")
(f)
should give
hello, world
Exiting...
While
(f)
(display "bye, world\n")
should give
Not done yet...
bye, world
I have thought about using control operators such as shift / reset, but with no success. The key difficulty seems to be that there is no way to tell if the current continuation is terminating. Any idea?
A continuation is never empty. What happens after the end is implementation specific but there is always some sort of resource deallocation and shutdown.
So imagine you have the following code which I had high hopes for:
(call/cc (lambda (end)
(define (f)
(call/cc (lambda (c)
(if (eq? c end)
(display "bye, world\n")
(display "Not done yet...")))))
(f)
(display "hello, world\n")
(f)))
Now you are not guaranteed that the continuation c and end can be compared even if they ae the same continuation. This has to do with the language details that upto R6RS there were no way to compare two procedures and that we aren't really comparing procedures so the implementation might have open coded their halt continuation such that it gets wrapped in a lambda and thus you are really comparing (eq? (lambda (v) (halt)) (lambda (v) (halt))) and it is not guaranteed to be #t or #f.
I am attempting to write a loop in Scheme using named let. I would like to be able to break out of the iteration early based on various criteria, rather than always looping right at the end. Effectively, I would like to have while, break and continue. I am constrained to use guile 1.8 for strong reasons, and guile 1.8 does not implement the R6RS while construct. My question is, does recursing using named let have to be tail recursive, and why can't you restart the loop before the end? [Does this need a code example?] When I do attempt to recurse using an early exit at several point with IO operations I invariably read past EOF and get unpredictable corruption of data.
(let name ((iter iter-expr) (arg1 expr1) (arg2 expr2))
(cond
(continue-predicate (name (next iter) arg1 arg2)))
(break-predicate break-expression-value)
(else (name (next iter) next-arg1-expression next-ar2-expression))))
A continue is just calling again using most of the same arguments unchanged except the iterated parts which will change to the next thing.
A break is a base case.
So what is a while? It is a named let with a break predicate and a default case.
Scheme doesn't really have a while construct. If you read the report you'll see that it is just a syntax sugar (macro) that turns into something like a named let.
You need it to be tail recursive if you want to be able to exit it without all the previous calculations to be done. You can also use call/cc to supply an exit continuation which is basically having Scheme doing it for you under the hood. Usually call/cc is quite far out for beginners and it takes some time to master so making your procedures tail recursive is easier to understand than doing something like this:
(define (cars lists-of-pair)
(call/cc (lambda (exit)
(fold (lambda (e a)
(if (pair? e)
(cons (car e) a)
(exit '()))) ; throw away continuations to make current result make it ()
'()
lists-of-pair)))
(cars '((1 2) (a b))) ; ==> (1 a)
(cars '((1 2) ())) ; ==> ()
I am brand spanking new to scheme. To the extent that tonight is the first time I've ever played around with it aside from what a powerpoint slide explained to me in class. I have to write a scheme program that takes a user input operator and then performs that operation on the numbers that follow it. (in other words implement my own version of schemes built-in '+', '*', etc operators). The catch is that I have to use recursion. Trying to maneuver my way around this scheme syntax is making it very difficult for me to even figure out where to start.
So, I decided to start with some code that at least recursively sums up values entered by the user (without worrying about recognizing the user inputting an operator and parentheses). I just plain can't figure out how to make it work. Here's what I'm trying:
(define run (lambda (x)
(cond
((eqv? x "a") (display x) )
(else (+ x (run(read))))
)))
(run (read))
The condition to check if x equals "a" was intended to be a way for me to break the recursion right now. In the final version, the input will be in between a set of parenthesis, but I thought I'd cross that bridge when I come to it. Anyways, the code just keeps accepting input, and never stops. So, the condition to display x is never getting called I guess. I know I'm probably doing everything wrong, and I would really appreciate some pointers.
EDIT: OK, I'm at least starting to realize that something isn't making sense. Such as my displaying x won't actually give the sum since I'm not storing the sum in x in any way. However, I still don't understand why the code isn't at least stopping when I enter the letter a.
EDIT 2: I've got it to work but only when the condition is equal to 1. How can I get it to recognize an input of a char or better yet a right parenthesis to get it to end the recursion just like it is with the 1? :
(define run (lambda (x)
(cond
((eq? x 1) 0)
(else (+ x (run(read))))
)))
(run (read))
End-Of-File (EOF) marks the end of input. Scheme has a procedure eof-object? for this. Your code is basically correct:
(define (run x)
(if (eof-object? x)
0
(+ x (run (read)))))
You end the run using Control-D. If for some reason you don't have access to eof-object? just use a special character like X. In that case your test would be (eq? x #\X)
(define (addition-loop)
(let ((answer (read)))
(if (number? answer)
(+ answer (addition-loop))
0)))
This will break as soon as you enter something that isn't a number.
In addition as you can see, you can have a function of zero arguments.
Anyways the problem with your code is when you enter a into read, it's value it actually the same a 'a or (quote a), rather than "a".
(eqv? 'a "a")
;Value: #f
In Clojure programming language, why this code passes with flying colors?
(let [r (range 1e9)] [(first r) (last r)])
While this one fails:
(let [r (range 1e9)] [(last r) (first r)])
I know it is about "Losing your head" advice but would you please explain it to me? I'm not able to digest it yet.
UPDATE:
It is really hard to pick the correct answer, two answers are amazingly informative.
Note: Code snippets are from "The Joy of Clojure".
To elaborate on dfan and RafaĆ's answers, I've taken the time to run both expressions with the YourKit profiler.
It's fascinating to see the JVM at work. The first program is so GC-friendly that the JVM really shines at managing its memory.
I drew some charts.
GC friendly: (let [r (range 1e9)] [(first r) (last r)])
This program runs very low on memory; overall, less than 6 megabytes. As stated earlier, it is very GC friendly, it makes a lot of collections, but uses very little CPU for that.
Head holder: (let [r (range 1e9)] [(last r) (first r)])
This one is very memory hungry. It goes up to 300 MB of RAM, but that's not enough and the program does not finish (the JVM dies less than one minute later). The GC takes up to 90% of CPU time, which indicates it desperately tries to free any memory it can, but cannot find any (the objects collected are very little to none).
Edit The second program ran out of memory, which triggered a heap dump. An analysis of this dump shows that 70% of the memory is java.lang.Integer objects, which could not be collected. Here's another screenshot:
range generates elements as needed.
In the case of (let [r (range 1e9)] [(first r) (last r)]), it grabs the first element (0), then generates a billion - 2 elements, throwing them out as it goes, and then grabs the last element (999,999,999). It never has any need to keep any part of the sequence around.
In the case of (let [r (range 1e9)] [(last r) (first r)]), it generates a billion elements in order to be able to evaluate (last r), but it also has to hold on to the beginning of the list it's generating in order to later evaluate (first r). So it's not able to throw anything away as it goes, and (I presume) runs out of memory.
What really holds the head here is the binding of the sequence to r (not the already-evaluated (first r), since you cannot evaluate the whole sequence from its value.)
In the first case the binding no longer exists when (last r) is evaluated, since there are no more expressions with r to evaluate. In the second case, the existence of the not-yet-evaluated (first r) means that the evaluator needs to keep the binding to r.
To show the difference, this evaluates OK:
user> (let [r (range 1e8) a 7] [(last r) ((constantly 5) a)])
[99999999 5]
While this fails:
(let [r (range 1e8) a 7] [(last r) ((constantly 5) r)])
Even though the expression following (last r) ignores r, the evaluator is not that smart and keeps the binding to r, thus keeping the whole sequence.
Edit: I have found a post where Rich Hickey explains the details of the mechanism responsible for clearing the reference to the head in the above cases. Here it is: Rich Hickey on locals clearing
for a technical description, go to http://clojure.org/lazy. the advice is mentioned in the section Don't hang (onto) your head
This a conceptual question on how one would implement the following in Lisp (assuming Common Lisp in my case, but any dialect would work). Assume you have a function that creates closures that sequentially iterate over an arbitrary collection (or otherwise return different values) of data and returns nil when exhausted, i.e.
(defun make-counter (up-to)
(let ((cnt 0))
(lambda ()
(if (< cnt up-to)
(incf cnt)
nil))))
CL-USER> (defvar gen (make-counter 3))
GEN
CL-USER> (funcall gen)
1
CL-USER> (funcall gen)
2
CL-USER> (funcall gen)
3
CL-USER> (funcall gen)
NIL
CL-USER> (funcall gen)
NIL
Now, assume you are trying to permute a combinations of one or more of these closures. How would you implement a function that returns a new closure that subsequently creates a permutation of all closures contained within it? i.e.:
(defun permute-closures (counters)
......)
such that the following holds true:
CL-USER> (defvar collection (permute-closures (list
(make-counter 3)
(make-counter 3))))
CL-USER> (funcall collection)
(1 1)
CL-USER> (funcall collection)
(1 2)
CL-USER> (funcall collection)
(1 3)
CL-USER> (funcall collection)
(2 1)
...
and so on.
The way I had it designed originally was to add a 'pause' parameter to the initial counting lambda such that when iterating you can still call it and receive the old cached value if passed ":pause t", in hopes of making the permutation slightly cleaner. Also, while the example above is a simple list of two identical closures, the list can be an arbitrarily-complicated tree (which can be permuted in depth-first order, and the resulting permutation set would have the shape of the tree.).
I had this implemented, but my solution wasn't very clean and am trying to poll how others would approach the problem.
Thanks in advance.
edit Thank you for all the answers. What I ended up doing was adding a 'continue' argument to the generator and flattening my structure by replacing any nested list with a closure that permuted that list. The generators did not advance and always returned the last cached value unless 'continue' was passed. Then I just recursively called each generator until I got to the either the last cdr or a nil. If i got to the last cdr, I just bumped it. If I got to a NIL, I bumped the one before it, and reset every closure following it.
You'll clearly need some way of using each value returned by a generator more than once.
In addition to Rainer Joswig's suggestions, three approaches come to mind.
Caching values
permute-closures could, of course, remember every value returned by each generator by storing it in a list, and reuse that over and over. This approach obviously implies some memory overhead, and it won't work very well if the generated sequences can be infinite.
Creating new generators on each iteration
In this approach, you would change the signature of permute-closures to take as arguments not ready-to-use generators but thunks that create them. Your example would then look like this:
(permute-closures (list (lambda () (make-counter 3))
(lambda () (make-counter 3))))
This way, permute-closures is able to reset a generator by simply recreating it.
Making generator states copyable
You could provide a way of making copies of generators along with their states. This is kind of like approach #2 in that permute-closures would reset the generators as needed except the resetting would be done by reverting to a copy of the original state. Also, you would be able to do partial resets (i.e., backtrack to an arbitrary point rather than just the beginning), which may or may not make the code of permute-closures significantly simpler.
Copying generator states might be a bit easier in a language with first-class continuations (like Scheme), but if all generators follow some predefined structure, abstracting it away with a define-generator macro or some such should be possible in Common Lisp as well.
I would add to the counter either one of these:
being able to reset the counter to the start
letting the counter return NIL when the count is done and then starting from the first value again on the next call