Lisp - Flag(bandera) don't funtion - loops

I'm trying to write a function to determine whether a word is palindrome or not. I make this but it always returns "Is not a palindrome". I don't know what is happening.
(defun palindromo (X)
(setq i 0)
(setq j (- (length X) 1))
(setq bandera 0)
(loop while (< j i)
do
(when (char= (char X i) (char X j))
(+ i 1)
(- j 1)
(setq bandera 1))
(unless (char/= (char X i) (char X j))
(setq bandera 0)
)
)
(cond
((equal 0 bandera) (write "Is not a palindrome"))
((equal 1 bandera) (write "Is a palindrome"))
)
)
How can I fix this?

 Loop problem
Your loop termination test is while (< j i), but you previously set i and j to respectively the index of the first and last character. That means that (<= i j). You never execute the body of the loop, and bandera is never modified from its initial value, 0.
Infinite loop problem
But suppose you fix your test so that it becomes (< i j), then your loop becomes an infinite loop, because you never mutates either i nor j in the body of your loop. The two expressions (+ i 1) and (- j 1) only computes the next indices, but do not change existing bindings. You would have to use setq, just as you did above.
Invalid use of SETQ
By the way, you cannot introduce variables with setq: it is undefined what happens when trying to set a variable that is not defined. You can introduce global variables with defvar, defparameter, and local variables with, among others, let, let* and the loop keyword with.
I assume your Common Lisp implementation implicitly defined global variables when you executed or compiled (setq i 0) and other assignments. But this is far from ideal since now your function depends on the global state and is not reentrant. If you called palindromo from different threads, all global variables would be modified concurrently, which would give incorrect results. Better use local variables.
Boolean logic
Do not use 0 and 1 for your flag, Lisp uses nil as false and everything else as true for its boolean operators.
Confusing tests
In the loop body, you first write:
(when (char= (char X i) (char X j)) ...)
Then you write:
(unless (char/= (char X i) (char X j)) ...)
Both test the same thing, and the second one involves a double-negation (unless not equal), which is hard to read.
Style
You generally do not want to print things from utility functions.
You should probably only return a boolean result.
The name of X is a little bit unclear, I'd would have used string.
Try to use the conventional way of formatting your Lisp code. It helps to use an editor which auto-indents your code (e.g. Emacs). Also, do not leave dangling parentheses on their own lines.
Rewrite
(defun palindromep (string)
(loop with max = (1- (length string))
for i from 0
for j downfrom max
while (< i j)
always (char= (char string i)
(char string j))))
I added a p to palindrome by convention, because it is a predicate.
The with max = ... in the loop defines a loop variable which holds the index of the last character (or -1 if string is empty).
i is a loop variable which increments, starting from 0
j is a loop variable which decrements, starting from max
the whileis a termination test
always evaluates a form at each execution of the loop, and check whether it is always true (non-nil).

Actually, no externally defined loop is needed for finding out, whether a string is palindromic or not. [ Remark: well, I thought that in the beginning. But as #coredump and #jkiiski pointed out, the reverse function slows down the procedure, since it copies the entire string once. ]
Use:
(defun palindromep (s)
(string= s (reverse s)))
[ This function will be way more efficient than your code
and it returns T if s is palindromic, else NIL.] (Not true, it only saves you writing effort, but it is less efficient than the procedure using loop.)
A verbose version would be:
(defun palindromep (s)
(let ((result (string= s (reverse s))))
(write (if result
"Is a palindrome"
"Is not a palindrome"))
result))
Writes the answer you wish but returns T or NIL.
The naming convention for a test function returning T or NIL is to end the name with p for 'predicate'.
The reverse function is less performant than the while loop suggested by #coredump
This was my beginner attempt to test the speed [not recommendable]:
;; Improved loop version by #coredump:
(defun palindromep-loop (string)
(loop with max = (1- (length string))
for i from 0
for j downfrom max
while (< i j)
always (char= (char string i)
(char string j))))
;; the solution with reverse
(defun palindromep (s)
(string= s (reverse s)))
;; the test functions test over and over the same string "abcdefggfedcba"
;; 10000 times over and over again
;; I did the repeats so that the measuring comes at least to the milliseconds
;; range ... (but it was too few repeats still. See below.)
(defun test-palindrome-loop ()
(loop repeat 10000
do (palindromep-loop "abcdefggfedcba")))
(time (test-palindrome-loop))
(defun test-palindrome-p ()
(loop repeat 10000
do (palindromep "abcdefggfedcba")))
(time (test-palindrome-p))
;; run on SBCL
[55]> (time (test-palindrome-loop))
Real time: 0.152438 sec.
Run time: 0.152 sec.
Space: 0 Bytes
NIL
[56]> (time (test-palindrome-p))
Real time: 0.019284 sec.
Run time: 0.02 sec.
Space: 240000 Bytes
NIL
;; note: this is the worst case that the string is a palindrome
;; for `palindrome-p` it would break much earlier when a string is
;; not a palindrome!
And this is #coredump's attempt to test the speed of the functions:
(lisp-implementation-type)
"SBCL"
(lisp-implementation-version)
"1.4.0.75.release.1710-6a36da1"
(machine-type)
"X86-64"
(defun palindromep-loop (string)
(loop with max = (1- (length string))
for i from 0
for j downfrom max
while (< i j)
always (char= (char string i)
(char string j))))
(defun palindromep (s)
(string= s (reverse s)))
(defun test-palindrome-loop (s)
(sb-ext:gc :full t)
(time
(loop repeat 10000000
do (palindromep-loop s))))
(defun test-palindrome-p (s)
(sb-ext:gc :full t)
(time
(loop repeat 10000000
do (palindromep s))))
(defun rand-char ()
(code-char
(+ #.(char-code #\a)
(random #.(- (char-code #\z) (char-code #\a))))))
(defun generate-palindrome (n &optional oddp)
(let ((left (coerce (loop repeat n collect (rand-char)) 'string)))
(concatenate 'string
left
(and oddp (list (rand-char)))
(reverse left))))
(let ((s (generate-palindrome 20)))
(test-palindrome-p s)
(test-palindrome-loop s))
Evaluation took:
4.093 seconds of real time
4.100000 seconds of total run time (4.068000 user, 0.032000 system)
[ Run times consist of 0.124 seconds GC time, and 3.976 seconds non-GC time. ]
100.17% CPU
9,800,692,770 processor cycles
1,919,983,328 bytes consed
Evaluation took:
2.353 seconds of real time
2.352000 seconds of total run time (2.352000 user, 0.000000 system)
99.96% CPU
5,633,385,408 processor cycles
0 bytes consed
What I have learned from that:
- Test more rigorously, repeat as often as necessary (range of seconds)
- do random generation and then test in parallel
Thank you very much for the nice example #coredump! And for the remark #jkiiski!

Related

What is the closest equivalent to a for-loop in Racket-sdp?

Is recursion the only way to write something like a for-loop in the Racket dialect sdp ("Schreibe dein Programm!"), in which "(for)" isn't a thing or is there a more "efficient" or simpler way to do so?
What would the closest equivalent to the C++ loop for(i = 0 , i < 100, i++) look like in Racket-sdp code?
How I did this up until now was:
(: my-loop (natural -> %a))
(define my-loop
(lambda (i)
(cond
[(< i 100) (my-loop (+ i 1))] ; <-- count up by one till 99 is reached
[else "done"] ; <-- end
)))
(my-loop 0)
EDIT:
It's more of a general question. If I were to write lets say a raket library which contains a general function, that might be used like this:
(for 0 (< i 100) (+ i 1) (func i))
in my programs which is a for-loop that runs with a given function as it's "body", would there be a way to implement this properly?
[Professor of the mentioned course here.]
Recursion indeed is the only way to express iterated computation in the Racket dialect we are pursuing. (Yes, that's by design.)
Still, higher-order functions (and recursion) provide all you need to create your own "loop-like control structures". Take the following HOF, for example, which models a repeat-until loop:
(: until ((%a -> boolean) (%a -> %a) %a -> %a))
(define until
(lambda (done? f x)
(if (done? x)
x
(until done? f (f x)))))
Note that the until function is tail-recursive. You can expect it to indeed behave like a loop at runtime — a clever compiler will even translate such a function using plain jump instructions. (We'll discuss the above in the upcoming Chapter 12.)
You can make a high-order for-loop.
Here is an simple example:
(define (for start end f)
(define (loop i)
(when (< i end)
(f i)
(loop (+ i 1))))
(loop start))
(for 0 10 (λ (i) (displayln i)))
You can make this more general if you use a next function instead of (+ i 1) and use a while-predicate? function instead of (< i end).

Lisp Loop Largest Number

I've been fiddling with Lisp programs for a little while and one thing that I can never seem to figure out is how to use a loop on a list inside a function. I'm trying to create a function that will take a list as the parameters while using a do... loop. I know how to do it with if statements but now I need to use a loop. Does anyone have a clue on how to do that?
(defun maximum (a_list)
(if (= (length a_list) 1)
(car a_list)
(if (> (car a_list) (maximum (cdr a_list)))
(car a_list)
(maximum (cdr a_list))))
(format t "~d" a_list))
Here's what I have so far on the if statements. They might not work right but at least they work.
Here another set of possibilities, in addition to those proposed in another answers.
First of all, when writing a function, one should also test for special cases, while you do not check for an empty list. So the structure of the function could be something of this type:
(defun maximum (l)
(if (null l)
nil ; or give an error
...normal solution...))
In case of returning nil, this structure in Common Lisp is identical to the following one, given that and evaluates its arguments in sequence, and returns nil as soon as an argument is evaluated to nil, otherwise returns the value of the last argument:
(defun maximum (l)
(and l ...normal solution...))
Here the alternative solutions.
Without loop or recursion, with predefined functions reduce (manual) and max (manual).
(defun maximum (l)
(and l (reduce #'max l)))
With the construct dolist (manual), that iterates a variable over a list:
(defun maximum (l)
(and l (let ((result (car l)))
(dolist (x (cdr l) result)
(when (> x result)
(setf result x))))))
And finally, with a compact version of do (manual):
(defun maximum (l)
(and l (do ((maximum-so-far (car l) (max (pop l) maximum-so-far)))
((null l) maximum-so-far))))
With loop the solution is trivial:
(loop for x in '(1 2 7 4 5) maximize x)
I assume therefore that what you intend to do is to write the function with a do loop. In this case you have to traverse the list keeping track of the maximum element so far, and updating this value if you find a larger value:
(setq list '(1 2 7 4 5))
(do* ((l list (cdr l))
(x (car l) (car l))
(max x) )
((null l) max)
(if (> x max)
(setq max x) ))
(defun maximum (list)
(let ((result)) ;; short for ((result nil))
(dolist (x list)
(if result
(when (> x result)
(setf result x))
(setf result x)))
result))
(dolist (x list) ... ) is like Python's [... for x in list]
It is typical imperative style to create a variable with
let and setf to it to change its value.

Heap's algorithm in Clojure (can it be implemented efficiently?)

Heap's algorithm enumerates the permutations of an array. Wikipedia's article on the algorithm says that Robert Sedgewick concluded the algorithm was ``at that time the most effective algorithm for generating permutations by computer,'' so naturally it would be fun to try to implement.
The algorithm is all about making a succession of swaps within a mutable array, so I was looking at implementing this in Clojure, whose sequences are immutable. I put the following together, avoiding mutability completely:
(defn swap [a i j]
(assoc a j (a i) i (a j)))
(defn generate-permutations [v n]
(if (zero? n)
();(println (apply str a));Comment out to time just the code, not the print
(loop [i 0 a v]
(if (<= i n)
(do
(generate-permutations a (dec n))
(recur (inc i) (swap a (if (even? n) i 0) n)))))))
(if (not= (count *command-line-args*) 1)
(do (println "Exactly one argument is required") (System/exit 1))
(let [word (-> *command-line-args* first vec)]
(time (generate-permutations word (dec (count word))))))
For an 11-character input string, the algorithm runs (on my computer) in 7.3 seconds (averaged over 10 runs).
The equivalent Java program, using character arrays, runs in 0.24 seconds.
So I would like to make the Clojure code faster. I used a Java array with type hinting. This is what I tried:
(defn generate-permutations [^chars a n]
(if (zero? n)
();(println (apply str a))
(doseq [i (range 0 (inc n))]
(generate-permutations a (dec n))
(let [j (if (even? n) i 0) oldn (aget a n) oldj (aget a j)]
(aset-char a n oldj) (aset-char a j oldn)))))
(if (not= (count *command-line-args*) 1)
(do
(println "Exactly one argument is required")
(System/exit 1))
(let [word (-> *command-line-args* first vec char-array)]
(time (generate-permutations word (dec (count word))))))
Well, it's slower. Now it averages 9.1 seconds for the 11-character array (even with the type hint).
I understand mutable arrays are not the Clojure way, but is there any way to approach the performance of Java for this algorithm?
It's not so much that Clojure is entirely about avoiding mutable state. It's that Clojure has very strong opinions on when it should be used.
In this case, I'd highly recommend finding a way to rewrite your algorithm using transients, as they're specifically designed to save time by avoiding the reallocation of memory and allowing a collection to mutable locally so long as the reference to the collection never leaves the function in which it was created. I recently managed to cut a heavily memory intensive operation's time by nearly 10x by using them.
This article explains transients fairly well!
http://hypirion.com/musings/understanding-clojure-transients
Also, you may want to look into rewriting your loop structure in a way that allows you to use recur to recursively call generatePermutations rather than using the whole name. You'll likely get a performance boost, and it'd tax the stack a lot less.
I hope this helps.

How to return a specific value in a loop

I am a complete novice to LISP I have the book Practical Common Lisp by Peter Seibel, but I couldn't find an answer to my question.
So basically how do I get this to return the value of the last ":do"
(defun averages (numbers)
(loop :for i :in numbers :sum i :into x :do (/ x (length numbers))))
Please bare in mind that I haven't been doing this very long.
Nor am I very aware of the unwritten do's and don't of Stackoverflow.
Use finally:
(defun averages (numbers)
(loop :for i :in numbers :sum i :into x
:finally (return (/ x (length numbers)))))
To avoid traversing the list twice, you can do (as suggested by #mark-reed and #joshua-taylor)
(defun averages (numbers)
(loop :for n :in numbers :sum n :into x :count t :into len
:finally (return (/ x len))))
but it will probably not make much difference performance-wise.
PS. You might want to consider CLOCC/CLLIB/math.lisp for your basic statistical needs.
If you don't make use of advanced features like multiple variables inside the LOOP, it's easy to simplify it:
(defun averages (numbers)
(loop for i in numbers sum i into x
finally (return (/ x (length numbers)))))
Just take advantage that the LOOP form returns the sum:
(defun averages (numbers)
(/ (loop for i in numbers sum i)
(length numbers)))
It might also be useful to check for an empty list of numbers first.

Scheme while loop

I'm kinda new in scheme syntax... I'm trying to make a simple program where you input an integer, if the integer is even do something and if it's odd do something else.
I was able to do this part. Now, I need to make a loop where I can decrement the number until it equals to 1.
Here is my code :
#lang racket
(define (even? n)
(if (eqv? n 0) #t
(odd? (- n 1))))
(define (odd? n)
(if (eqv? n 0) #f
(even? (- n 1))))
; this is the function that i wanted to be inside the loop
(define (sequence n)
(cond
[(even? n) n( / n 2)]
[(odd? n) n(+(* n 3) 1) ] )
)
(sequence 5)
The output should be a sequence of numbers. In other words, it should be inside a list.
An output list is built by consing each of the elements that are part of the list and then advancing the recursion over the input, until the input is exhausted (in your case, when the number n is one). By successively consing elements at the head of the list and ending the recursion with a null value, a new proper list is created and returned at the end of the procedure execution. Here's how:
(define (sequence n)
(cond [(= n 1) ; if n=1, it's the exit condition
(list n)] ; return a list with last element
[(even? n) ; if n is even
(cons n (sequence (/ n 2)))] ; cons n and advance the recursion
[(odd? n) ; if n is odd
(cons n (sequence (+ (* n 3) 1)))])) ; cons n and advance the recursion
The above will return a list with the Collatz sequence for the given number n:
(sequence 6)
=> '(6 3 10 5 16 8 4 2 1)
As a side note: the procedures even? and odd? are standard in Scheme and you don't have to redefine them.

Resources