Isearch return t if found for loop function in Emacs Lisp - function

How to write a function where whenever a variable is found, it returns t (in order to allow a loop):
(setq x 1)
(while ("backward search for regexp "%x" equals true") ;where x is variable
(setq x (+ x 1))
(insert (concat "%" (int-to-string x)))
)
Example: If %1 (x=1) is found, it will add 1 to x. If %2 (x=2) is found, it will add 1 to x.
Let's say %3 is not found in a backward search, the while loop stops and "%" + "3" is inserted (%3).
I just don't understand the how to return true on a backward-search.

search-backward takes an optional third argument which, when non-nil, tells it to return nil in case the search was unsuccessful:
(setq x 1)
(while (search-backward (format "%%%d" x) nil t)
(setq x (1+ x)))
(insert (format "%%%d" x))
Now, if I try to understand what you really want to do (something like inserting at point the first %d string which doesn't appear before), then you might want to wrap the search inside a save-excursion form to avoid moving the point:
(setq x 1)
(while (save-excursion (search-backward (format "%%%d" x) nil t))
(setq x (1+ x)))
(insert (format "%%%d" x))

With help from Francesco
(defun Navi-insert-question ()
(interactive)
(setq x 1)
(while (save-excursion
(search-backward (concat comment-start " Question: " (int-to-string x)) nil t))
(setq x (+ 1 x)))
(insert (concat comment-start " Question: " (int-to-string x))))
It now results in being able to insert in R, for instance: "# Question: 1", when it exists above in the buffer it will insert "# Question: 2".

Related

Where is the argument coming from?

You can notice the v in the lambda in the function body, where is the v coming from, what it is based on?
(define (cached-assoc xs n)
(letrec ([memo (make-vector n #f)]
[acc 0]
[f (lambda(x)
(let ([ans (vector-assoc x memo)])
(if ans
(cdr ans)
(let ([new-ans (assoc x xs)])
(begin
(vector-set! memo acc (cons x new-ans))
(set! acc (if (= (+ acc 1)) 0 (+ acc 1)))
new-ans)))))])
(lambda (v) (f v))))
The whole expression is returning a lambda as a result, and in that lambda there's a formal parameter named v. It doesn't have a value yet, you'll need to call the lambda to bind a value to v and produce a result (assuming the code is working):
((letrec ([memo (make-vector n #f)] ; notice the extra opening `(`, we want to call the returned lambda
[acc 0]
[f (lambda(x)
(let ([ans (vector-assoc x memo)])
(if ans
(cdr ans)
(let ([new-ans (assoc x xs)])
(begin
(vector-set! memo acc (cons x new-ans))
(set! acc (if (= (+ acc 1)) 0 (+ acc 1)))
new-ans)))))])
(lambda (v) (f v)))
10) ; <- the value 10 gets bound to `v`
However, your code isn't right. You are referring to variables named n and xs, but they are not defined anywhere and need a value of their own. The procedure vector-assoc doesn't exist. Also, the lambda at the end is redundant, you could simply return f, there's no need to wrap it in an additional lambda. Finally: you should define the whole expression with a name, it'll make it easier to call it.
I won't go into more details because first you need to fix the function and make it work, and is not clear at all what you want to do - but that should be a separate question.

Call a function while in a loop (Common Lisp)

I am making a console Lisp survival game and I am trying to add a function where until a = b, show "." every second. Then, when a = b, set a "hurt" variable to true, and if/when that variable is true, subtract "health" by 1 until the "use-medkit" function is invoked by the user and the "hurt" variable is set false and you exit both loops.
The problem I am having is when I am prompted to use the "use-medkit" function and I type it in, it doesn't evaluate anything that I input and keeps subtracting 1 from "health". How can I call a user-inputted function while a loop is running?
Here is my code:
(setq a (random 11)) ; Random from 0 - 10
(setq b (random 11)) ; ^^^^^^^^^^^^^^^^^^
(setq hurt 0)
(setq repair 0)
(setq health 999)
(defun use-medkit ()
(setq repair 1))
(defun get-hurt ()
(loop
(progn
(setq a (random 11))
(setq b (random 11))
(progn
(princ ".")
(sleep 1)))
(if (eq a b) (progn
(setq hurt 1)
(when (eq hurt 1) (progn
(format t "~%You are hurt!~%You will lose 1 hp every 10 seconds~%~%Type use-medkit to stop the bleeding~%")
(loop
(progn
(- 1 health)
(sleep 10))
;(format t "health: ~A~%" health)
(when (eq repair 1) (progn
(return "You stopped the bleeding") (setq hurt 0) (setq repair 0))))))))))
So a program can’t do two things at once. In particular if you’re busy printing dots, sleeping and subtracting 1 from 999 then you won’t pause to see if there’s another command coming.
Unfortunately solving this problem is hard. The nicest solution in a terminal would probably use something like ncurses. Additionally there is no standard way to control input buffering. In lieu of that, here is a simple way you can do a bit of concurrency and some prompts. You might want to use a proper async library instead.
(defun maybe-read (input-stream recording-stream)
(when (listen input-stream)
(let ((char (read-char input-stream)))
(if (char= char #\Newline)
t
(progn (write-char char recording-stream) (maybe-read))))))
(defun make-partial-reader (input-stream)
(list input-stream (make-string-output-stream)))
(defun partial-read (reader)
(when (apply #'maybe-read reader)
(get-output-stream-string (second reader))))
(defun how-long-until (time)
(let ((gap
(/ (- time (get-internal-run-time)) internal-time-units-per-second)))
(cond ((< gap 0) (values 0 :late))
((<= gap 0.001) (values 0 :now))
(T (values (- gap 0.001) :soon)))))
(defun sleep-until (time)
(multiple-value-bind (span type)
(how-long-until time)
(when (> span 60) (warn “long wait!”)
(case type
(:late nil)
(:now t)
(:soon
(sleep span)
(unless (sleep-until time) (warn “poor timekeeping”))
t))))
(defmacro with-prompt-and-scheduler ((schedule) (line &optional (input *standard-input*)) &body handle-line-input)
(let ((reader (gensym)) (insched (gensym)))
`(let ((,reader (make-partial-reader ,input) (,insched)))
(flet ((,schedule (in fun &aux (at (+ (get-internal-run-time) (* in internal-time-units-per-second))))
(if (null ,insched) (push (cons at fun) schedule)
(loop for s on ,insched
for ((at2) . y) = s
if (< at at2)
do (psetf (car s) (cons at fun)
(cdr s) (cons (car s) (cdr s)))
(finish-loop)
unless y do (setf (cdr s) (acons at fun nil)) (finish-loop)))))
(loop
(if ,insched
(let ((,insched (pop ,insched)))
(when (sleep-until (car ,insched))
(let ((,line (partial-read ,reader)))
(when ,line ,#handle-line-input)))
(funcall (cdr ,insched)))
(let ((,line (concatenate 'string (get-output-stream-string (second ,reader)) (read-line (first ,reader)))))
,#handle-line))))))))
And then you could use it like:
(let ((count 0))
(with-prompt-and-scheduler (schedule) (line)
(let ((n (read-from-string line)))
(when (realp n)
(schedule n (let ((x (incf count))) (lambda () (format t "Ding ~a ~a~%" x count) (finish-output))))))))
And after running that input 10, then on the next line 5. If you do that quickly you’ll get:
Ding 2 2
Ding 1 2
With the first line appearing after 5 seconds and the second after 10. If you are slow you should get:
Ding 1 1
Ding 2 2
With the first line coming 10 seconds after you enter 10 and the second line coming 5 seconds after you enter 5.
Hopefully this can give you an idea of how to make a program seem to do two things at once.

Make Scheme function for 3 parameters return function for the 3d

I'm having a hard time converting this rather simple Scheme function, into a function that returns another function taking in a list and applying the former function to all elements on that list.
This function
(define (operList op i lis)
(if (= 0 (length lis)) '()
(cons (op i (car lis)) (operList op i (cdr lis))))
)
Can be called like this
(operList + 2 '(1 1 1))
and returns '(3 3 3)
However, how can I edit this function so that I can call it in the following manner
((operList + 2) '(1 1 1))
with the same results
You have to return a new function that receives the list. I took the liberty of fixing the indentation and the base case (that's not how you should ask if a list if empty!); pay special attention to the way the recursion is called now:
(define (operList op i)
(lambda (lis)
(if (null? lis)
'()
(cons (op i (car lis))
((operList op i) (cdr lis))))))
It works as expected:
((operList + 2) '(1 1 1))
=> '(3 3 3)
You could also use map:
(define operList
(lambda (op i)
(lambda (lst)
(map
(lambda (x) (op i x))
lst))))

Scheme function doesn't return value

Here is what the function should do:
I am giving it list of "pairs" that look like (((a . b) . c) ((a . b) . c) ((a. b) . c) ...)
where:
a means if the vertex is visited 1 for yes 0 for no
b means what is the value of the shortest path to the vertex so far (if it is -1 it is infinity)
c is the number of the parent (if it has so far if it doesn't it is the number of the pair if you count the first pair for 1 second for 2 and etc.)
The function should return the number of the next unvisited pair (vertex) with the lowest cost of the path so far.
Example:
(((0 . 10) . 1) ((0 . 4) . 2) ((1 . 3) . 5) ...) here it should return the number 2.
Here is the code
(define (chooseNextLowest pairs num retV pointer)
(if (null? pairs)
retV
(if (checkIfPairVis (caar pairs))
(chooseNextLowest (cdr pairs) num retV (+ 1 pointer))
(if (= -1 num)
(chooseNextLowest (cdr pairs) (cdaar pairs) pointer (+ 1 pointer))
(if (not (= -1 (cdaar pairs)))
(if (< (cdaar pairs) num)
(chooseNextLowest (cdr pairs) (cdaar pairs) pointer (+ 1 pointer))
(chooseNextLowest (cdr pairs) num retV (+ 1 pointer))))))))
I have used some function that are predefined but I think it's clear by their names what they do.
I call it with num = -1 , retV = -1 and pointer = 1, since I use -1 for infinity and I am sure retV will be changed at least 1 time because everytime I call this function will be at least 1 unvisited pair.
They work fine also this function seems to work fine when I use it with some testPairs but when I use pairs that are returned from other function (since I have to choose everytime the lowest cost unvisited vertex after I update the information in the pairs) it doesnt return any value.
Maybe you will ask to see the other function too but I can't give it at the moment since if I give it I have to give the whole sorce code to make sense so I hope the mistake is somewhere here but I can't find it.
The other function return normal pairs in the type I want them ((a . b ) . c) and etc.
Thank you very much. I am sure I didn't make some things clear so If you have questions feel free to ask me.
After formatting the code it's obvious that in the second deepest if you are lacking a alternative. if without alternative is very new in Scheme but:
(if #f 'true) ;; ==> #undefined
Looking at your code, specially checkIfPairVis it seems you do caar and that's ok for the object, but not for the list with an object. The best way to eliminate such things would be to make accessors in your code which also will make your code easier to read:
(define (choose-next-lowest pairs num ret-v pointer)
;; accessor based on object
(define vertex-visited caar)
(define vertex-shortest cdar)
(define vertex-parents cdr)
(if (null? pairs)
ret-v
(let ((obj (car pairs)))
(cond
((check-if-pair-vis (vertex-visited obj))
(choose-next-lowest (cdr pairs) num ret-v (+ 1 pointer)))
...))))
After fixing that accessor I get 2 as you predicted.
It could be other things wrong of course. Seems to me you need to debug. In DrRacket IDE you could step through your code to ensure it works as designed.
PS: A named let will add accumulators and variables you don't need to expose:
(define (choose-next-lowest pairs)
(define vertex-visited caar)
(define vertex-shortest cdar)
(define vertex-parents cdr)
(define (vertex-visited? v)
(= 1 (vertex-visited v)))
(let rec ((pairs pairs) (num -1) (ret-v -1) (pointer 1))
(if (null? pairs)
ret-v
(let ((obj (car pairs)))
(cond
((vertex-visited? obj) (rec (cdr pairs) num ret-v (+ 1 pointer)))
((= -1 num) (rec (cdr pairs) (vertex-shortest obj) pointer (+ 1 pointer)))
((= -1 (vertex-shortest obj)) 'undefined) ;; something wrong here?
((< (vertex-shortest obj) num) (rec (cdr pairs) (vertex-shortest obj) pointer (+ 1 pointer)))
(else (rec (cdr pairs) num ret-v (+ 1 pointer))))))))
(choose-next-lowest '(((0 . 10) . 1) ((0 . 4) . 2) ((1 . 3) . 5))) ; ==> 2
Your conditional at (if (not (= -1 (cdaar pairs))) ... only has a consequent clause. Without an alternate clause the return of if is undefined (officially). Specifically:
(if (not (= -1 (cdaar pairs)))
(if (< (cdaar pairs) num)
(chooseNextLowest (cdr pairs) (cdaar pairs) pointer (+ 1 pointer))
(chooseNextLowest (cdr pairs) num retV (+ 1 pointer)))
<something here>)))))
Illustrating how if has an undefined return:
> (if #f 'yes 'no)
no
> (if #f 'yes)
> ; <= nothing printed as a return, just a prompt displayed.

How to loop while following-char equals string?

I am writing a function to uncomment regardless of mode. I want to delete all comment characters at the beginning of a line.
How do I make the snippet below loop until the following character is not equal to comment-start? (so basically have this "if" go on and on and on until following-char is not equal to comment-start anymore)
(if (string= (byte-to-string (following-char)) comment-start)
(progn (delete-forward-char 1)
(when (string= (byte-to-string (following-char)) " ")
(delete-forward-char 1))))
A while loop was easier than I thought:
(defun uncomment-mode-specific ()
"Uncomment region OR uncomment beginning of line comment OR uncomment end"
(interactive)
(if (region-active-p)
(uncomment-region (region-beginning) (region-end))
(back-to-indentation))
(setq scvar 0)
(setq scskipvar 0)
(while (= scvar 0)
(if (string= (byte-to-string (following-char)) comment-start)
(progn (delete-forward-char 1)
(when (string= (byte-to-string (following-char)) " ")
(delete-forward-char 1))
(setq scskipvar 1))
(setq scvar 1)))
(if (= scskipvar 0)
(progn (search-forward comment-start nil t)
(left-char 1)
(kill-line))
)
)