Printing contents of array LISP - arrays

Why does this code not print out the content of the array -
(defun loopfn (state)
(loop for x from 0 to 2 do
(loop for y from 0 to 2 do
(aref state x y))))
Here I am passing a 3x3 matrix which is built like this -
`(setq i (make-array '(3,3) :initial-contents '((0 1 3) (4 2 5) (7 8 6))))`
I am calling - (loopfn i)
Edit--------
#Greg
Thanks for pointing that out...
I had the following question..
Why does this print the output ...
(defun loopfn ()
(loop for x from 0 to 3 do
(if (eq x 2)(return (list x)))))
Where as this prints a nil...
(defun loopfn ()
(loop for x from 0 to 2 do
(loop for y from 0 to 2 do
(if (eq x 2)(return (list x y))))))
I am calling
(loopfn)

Your code does not print anything. That's also what you want - usually.
But you want functions to return something useful.
So you need to understand the difference between printing and having a REPL printing a return value.
CL-USER > 3
3
Above returns 3. The Read-Eval-Print-Loop prints the return value.
CL-USER > (print 3)
3
3
Above prints a newline and then two times the 3. Why?
The first is the side-effect of the PRINT call which prints the newline and then its argument.
The second is the REPL printing the return value.
Note also the EQ is not for numeric comparisons. Use EQL instead.
See: http://www.lispworks.com/documentation/lw50/CLHS/Body/f_eql.htm

As for your second question, (return ...) is equivalent to (return-from NIL ...) so you just return from your inner LOOP into the outer one. Use this instead:
[11]> (defun loopfn ()
(loop for x from 0 to 2 do
(loop for y from 0 to 2 do
(if (= x 2) (return-from loopfn (list x y))))))
[12]> (loopfn)
(2 0)
Another possibility is to collect more values than just one, as in
[36]> (defun loopfn ()
(loop for x from 0 to 2 nconc
(loop for y from 0 to 2
if (= y 2)
collect (list x y))) )
LOOPFN
[37]> (loopfn)
((0 2) (1 2) (2 2))

Your call to aref is getting the specified element, but you're not doing anything with it. You could stick it on to a list which is then returned:
(defun loopfn (state)
(let ((result '()))
(loop for x from 0 to 2 do
(loop for y from 0 to 2 do
(setf result (cons (aref state x y) result))))
result))
or you could just print it out:
(defun loopfn (state)
(loop for x from 0 to 2 do
(loop for y from 0 to 2 do
(format t "~a~%" (aref state x y)))))
The former is far more useful ; you want to return things which can then be further processed, and anything that gets passed to the top level will be printed out for you.
As long as you are using LOOP you can easily gather up your values with COLLECT, APPEND, etc., which is the idiomatic way to do it.

This was neatly covered in this forum topic.
The outer loop has no clause which would cause a return value.
Some code examples from that thread:
(defun print-2d-array-as-table (array)
(loop for i from 0 below (array-dimension array 0)
do (loop for j from 0 below (array-dimension array 1)
do (princ (aref array i j))
(if (= j (1- (array-dimension array 1)))
(terpri)
(princ #\Space)))))
and one loop:
(defun print-2d-array-as-table (array)
(loop for i below (array-total-size array) do
(if (zerop (mod i (array-dimension array 0)))
(terpri)
(princ #\Space))
(princ (row-major-aref array i))))

For your second question, in the loop that doesn't print, (eq x 2) is never true. You have modified the loop bounds from 0 to 3 to 0 to 2, so x never reaches 2. Since there is no explicit (return ...) executed, the function returns nil.

Related

How do I flatten params passed to recur?

I'm trying to learn about loop/recur. I wanted to pass the return vector from a function back to the loop and I've tried something like this:
(defn foo [x y]
[(dec x) y])
(loop [x 3 y 4]
(if (> x 0)
(do
(prn x y)
(recur (foo x y)))))
That gives:
1. Caused by java.lang.IllegalArgumentException
Mismatched argument count to recur, expected: 2 args, got: 1
Now I can change the loop parameters to this other form which works:
(defn foo [x y]
[(dec x) y])
(loop [[x y] [3 4]]
(if (> x 0)
(do
(prn x y)
(recur (foo x y)))))
I'd like to know if there's any way I could change the first code to leave the (loop [x 3 y 4] ...) but change the arguments passed to recur somehow. I guess I need something like the apply function, but I couldn't get that to work with recur, because recur is not a function.
There is no easy way around it. recur is a special
form and Clojures
way around the JVM not having easy access to TCO.
Therefor you can not use apply here (which would be a solution to call
a function with arguments from a list).
So you have to hold on to the result of foo and then recur with
those. Note beside: if with just one branch is just when.
(defn foo [x y]
[(dec x) y])
(loop [x 3 y 4]
(when (> x 0)
(prn x y)
(let [[x' y'] (foo x y)]
(recur x' y'))))
If your domain here really is [x y] (e.g. coordinates) my suggestion
would be to build your functions around that and don't jump between
sometimes using a vector and sometimes passing x/y.
you could also make up a simple macro for that purpose.. maybe like this (which is basically a macro rewrite of your vectorized params variant):
(defmacro loop1 [bindings & body]
(let [left-side (vec (take-nth 2 bindings))
right-side (vec (take-nth 2 (rest bindings)))]
`(loop [~left-side ~right-side]
~#body)))
(loop1 [x 3 y 4]
(if (> x 0)
(do
(prn x y)
(recur (foo x y)))))
;;=> 3 4
;; 2 4
;; 1 4
nil
so, if you have repetitive usage pattern alike that, this macro could be a nice utility.

scheme loop does not iterate through all elements in the list

I am trying to change the elements on a list based on a criteria. Let's say I have a list,
L = '(0 1 1 0 0). I want only the first "zero" found in this list as "zero", and for any other "zero" in that list, I want them to be 1. So the list of my example will become L = '(0 1 1 1 1). This is what I have done so far,
(let dLoop ((L '(0 1 1 0 0))
(i 0)
(j 1))
(if (and (<= i (length L)) (<= j (- (length L) 1)))
(begin
(if (zero? (list-ref L i))
(begin
(cond
[(zero? (list-ref L j)) (list-set L j 1)]
[else (dLoop L i (add1 j))]
)
)
(dLoop L (add1 i) (add1 j))))
L))
This only returns, L = '(0 1 1 1 0)
For some reason, the moment it finds the first duplicate zero, the code terminates! I would really appreciate some insights regarding this issue
In your (cond) expression, you don't have a recursive call to dLoop if (zero? (list-ref L j)) case evaluates. This causes the (cond) to return, then the (begin) returns and finally exits out of you (let) expression. Adding on to what Lazer said however, this is kinda not the standard scheme approach, let alone very efficient since (list-ref) on linked-lists is O(n) each time. Perhaps try something like:
(define (find-and-map-rest lst pred f)
(cond [(null? lst) lst]
;; found the thing
[(pred (car lst)) (cons (car lst)
(map f (cdr lst)))]
;; didn't find the thing... yet
[else (cons (car lst)
(find-and-map-rest (cdr lst)
pred f))]))
(define (zero->one x)
(if (zero? x) 1 x))
(find-and-map-rest '(0 1 1 0 0) zero? zero->one)
Realistic code is probably not going to do all of that consing for a task like this. All that the code really needs to do is find the first zero, take the first part of the list up to and including that zero, and append it to a list of ones as long as the rest of the input list. If no zero is found, the result is just the input list:
(define (f xs)
(let ((rest (member 0 xs)))
(if rest
(let ((ones-count (sub1 (length rest))))
(append (take xs (- (length xs) ones-count))
(make-list ones-count 1)))
xs)))
Sample interaction:
scratch.rkt> (f '(0))
'(0)
scratch.rkt> (f '(1))
'(1)
scratch.rkt> (f '(0 1 1 0 0))
'(0 1 1 1 1)
scratch.rkt> (f '(1 1 0 1 1 1 0 0 1 0 1 0))
'(1 1 0 1 1 1 1 1 1 1 1 1)

Clojure - Fibonacci using loop recur - comes to infinite loop

I'm trying to get a Fibonacci numbers using loop-recur construction:
(defn fibo-looprecur [x]
(loop [current 0
next 1
result x]
(if (= x 0) current (recur next (+' current next) (dec result))))
)
When I run it, it works OK with 0, but when I put 1 to fibo-looprecur, it goes to an infinite loop. What could cause that behaviour?
Clojure works with values not reference types; in other words x and result do not point to the same value but are separate bindings. When you decrement result it has no effect on x, and therefore you never hit your base case of x = 0.
If you change your condition to check result instead of x you'll get the expected results.
(defn fibo-looprecur [x]
(loop [current 0
next 1
result x]
(if (= result 0) current (recur next (+' current next) (dec result)))))
(map fibo-looprecur (range 10))
=> (0 1 1 2 3 5 8 13 21 34)

Common Lisp - apply function to every other element in list

I want to apply the function (* x 2) to every other element in a list and return the entire list using the loop macro. The solution I've come up with so far is this:
(defun double-every-other (xs)
(loop for x in xs by #'cddr collect (* x 2)))
However, this will double every other element and only return the elements that were doubled, so if I executed:
(double-every-other '(1 2 3 4))
The result would be:
'(4 8)
But I want the result to be:
'(1 4 3 8)
Is there a way I can do this using (loop)?
Another version with less math:
(defun double-every-other (list)
(loop
for (a b) on list by #'cddr
collect a
when b collect (* b 2)))
(double-every-other '(1 2 3 4))
=> (1 4 3 8)
(double-every-other '(1 2 3 4 5))
=> (1 4 3 8 5)
Obviously, you won't be able to abstract the N as easily as the other answer (if you are thinking "macro", stop now). Here we iterate using the on keyword, which means each sublist is visited in turn. Since we use by #'cddr, every other sublist is skipped. The destructuring syntax (a b) binds the first and second elements of the visited list.
You can for instance test an integer increasing while the list is scanned:
(defun double-every-other (xs)
(loop for x in xs
for i from 1
if (oddp i)
collect x
else collect (* x 2)))
(defun double-every-other (xs)
(loop for x in xs
for doublep = nil then (not doublep)
collect (if doublep (* x 2) x)))
another version, without loop at all:
(defun make-cycled (&rest items)
(setf (cdr (last items)) items))
(mapcar #'funcall
(make-cycled #'identity (lambda (x) (* 2 x)))
'(10 9 8 7 6 5 4 3))
;;=> (10 18 8 14 6 10 4 6)
You could use the loop "on" list iteration primitive. This takes a list of loop variables that will be "smeared" across the list, with the last being the tail of the entire remaining list. The conditional loop for is necessary to avoid multiplying nil if we have an odd number of arguments.
(defun double-every-other (list)
(loop for (single double tail) on list by #'cddr
if (null double)
collect single
else
append (list single (* 2 double))))
And if we try to run it:
* (double-every-other '(1 2 3 4 5))
(1 4 3 8 5)

Clojure multiply first n elements in sequence by 'x' non recursive

I am a newbie in clojure and came across a problem which says, multiply first n elements in a sequence by some number 'x' (non recursively). So for example
(multiply-n-by-x [1 2 3 4 5] 2 10) => [10 20 30 4 5]
So here i understood that i need to loop over the sequence n times and then stop, but i am unable to do that. If someone could guide me on how to do about it, it would be great.
Same as Shawn's answer but with destructuring and split-at (a bit less redundant):
(defn multiply-n-by-x [s n x]
(let [[s1 s2] (split-at (inc n) s)]
(concat (map #(* x %) s1) s2)))
I think the easy way is :
(defn multiply-n-by-x [seq n m]
(concat (map #(* m %) (take (inc n) seq)) (drop (inc n) seq) )
)
This does what you want:
(defn multiply-n-by-x [sq n x]
(for [i (range (count sq)) ;for i in range 0 to number of elements in sq
:let [element (nth sq i)]] ;bind element to the nth item in sq
(if (<= i n) ;if index below n, return the multiplied element, otherwise return the element as is
(* x element)
element)))
whatever you return inside the for macro gets put into a sequence so the end result is collection.
Lazy sequences capture delayed recursion. take, drop, split and for are lazy constructions. We can avoid them by computing the altered head of the sequence eagerly, as follows:
(defn multiply-n-by-x [coll n x]
(loop [head [], coll coll, n n]
(if (and (seq coll) (>= n 0))
(recur (conj head (* (first coll) x)) (rest coll) (dec n))
(concat head coll))))
For example,
(multiply-n-by-x [1 2 3 4 5] 2 10)
;(10 20 30 4 5)
By the way, the convention in Clojure is to give the count of a slice, not the index of the final element, which is one less.
(range 3)
;(0 1 2)

Resources