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)
Related
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)
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)
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)
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.
I am trying to set each element of a vector equal to 3 by looping. I get:
java.lang.ClassCastException: clojure.lang.PersistentVector can
not be cast to java.lang.Number
This is the code.
(def w [1 2 3])
(defn update [index value]
(assoc w index value))
(loop [i -1]
(if (< (count w) i)
w
(recur (update (+ i 1) 3))))
Your update function doesn't work the way you expect.
(assoc w index value)
Produces a new vector based on w, except that the element at index is now value. It doesn't change w.
user> (def w [1 2 3])
user> (assoc w 0 9)
[9 2 3]
user> w
[1 2 3]
Also, you're not using loop/recur correctly. You begin the loop with i bound to -1, intending to use it as an index into w, but recur calls the loop not with the next value of i, but rather with an altered copy of w as returned by update.
Try something more like:
(def w [1 2 3])
(loop [i 0, v w]
(if (< (count w) i)
v
(recur (inc i) (assoc v i 3))))
But, since you're not actually using the index to compute the new value of the element, you can use map instead of loop. Since just setting each element to a constant value without considering its old value, you can use clojure's built-in function constantly.
(vec (map (constantly 3) w))
Map returns a sequence, I've wrapped it in a call to vec to transform it back into a vector.
You are mixing integer and vector type by passing (update ...) to recur function. The loop statement should be look like (loop [i -1 w w] ..) and then you could collect your new vector into the local "w". If you want to use recure statement this code can help you (I guess there are a lot of other options to change values of a vector):
(let [value 4
w [1 2 3]]
(loop [i 0
w w]
(if (< i (count w))
(recur (inc i) (assoc w i value))
w)))
You can do this with map and constantly:
(def w [1 2 3])
(map (constantly 3) w)
=> (3 3 3)
Note that this doesn't change w - it returns a new sequence of threes that is the same length as w. Therefore you could equally get the same result by using:
(repeat (count w) 3)
=> 3
If you actually want to change w, then I would suggest making w into an atom so it can be updated with a swap! function:
(def w (atom [1 2 3]))
(swap! w
(fn [old-w]
(vec (map (constantly 3) old-w))))
#w
=> [3 3 3]
Finally, if you really want to update the elements of w one at a time, you can do something like:
(dotimes [i (count #w)]
(swap! w
(fn [previous-w]
(assoc previous-w i 3))))
This seems rather unidiomatic and imperative in Clojure, but it does work.....