Iam another Clojure-newbi!
How can i assign a vector containing some values to another one?
I want to do:
[a b] >>> [b (+ a b)]
so that afterwards b has the value of (a+b) and a that of b.
It looks like you're trying to do a fibonacci sequence.
user=> (def fibseq (map first (iterate (fn [[a b]] [b (+ a b)]) [1 1])))
#'user/fibseq
user=> (take 10 fibseq)
(1 1 2 3 5 8 13 21 34 55)
What you've got to remember in clojure is immutability, so you don't change a and b to be the new values. So something like:
user=> (defn next-fib [[a b]]
(let [na b
nb (+ a b)]
[na nb]))
user=> (next-fib [1 2])
[2 3]
would produce a function next-fib that would return the next 2 values from your input. During the function, a and b cannot be changed, they are immutable, hence assignment to new values.
Here, i'm using destructuring to immediately break the elements of the input vector into values a and b, which are then used to calculate the next element, and is the same as how the 1 liner at the top of my answer works.
Or if you're doing looping, you can recur with values that get substitute over their previous iteration, this is not changing a and b (during any iteration their values are fixed and still immutable), but redoing the entire stack with new values in their place, subtle difference. See articles on tail recursion.
user=> (loop [a 1 b 1]
(if (< a 20)
(recur b (+ a b))
[a b]))
[21 34]
Here's a simple version of the Fibonacci Sequence using recur, it returns the first n numbers.
(defn fib-recur [n]
(loop [fib [] x n a 0 b 1]
(if (zero? x)
fib
(recur (conj fib b) (dec x) b (+ a b)))))
It works by starting with an empty array of numbers it's building, then recurs by decrementing the counter (x) from n to 0, each iteration changes a and b to be new values as part of the recursion, and it adds the latest number to the array fib returning that when the counter gets to zero.
Related
I'm trying to get the lowest integer out of a vector only containing numbers. I know how to do it with lists. You compare the first two values of the list and depending on which is larger you either save your value to output it later or call the function again with the rest of the list (all elements except the first) using the cdr procedure.
But with vectors I'm completely lost. My guess would be that the way of thinking about the solution would be the same for lists and vectors. I've been reading on the racket-lang website but haven't been able to come up with a solution to the problem. The procedures I've been experimenting most with are vector-ref and vector-length as they seem to be the most useful in this problem (but this is my first time working with vectors so what do I know).
So my two questions are:
How can we get all values except the first from a vector? Is there a procedure like cdr but for vectors?
If you were working with lists you would use cons to save the values you would want to output. But is there a similar way of doing it when working with vectors?
Thanks!
The simplest solution is to use a variant of for called for/fold.
I thought there were an for/min but alas.
#lang racket
(define v (vector 11 12 13 4 15 16))
(for/fold ([m +inf.0]) ([x (in-vector v)])
(min m x))
If you like a more explicit approach:
(define (vector-min xs)
(define n (vector-length xs))
(let loop ([i 0] ; running index
[m +inf.0]) ; minimum value so far
(cond
[(= i n) ; if the end is reached
m] ; return the minimum
[else ; else
(define x (vector-ref v i)) ; get new element in vector
(loop (+ i 1) ; increment index
(min m x))]))) ; new minimum
UPDATE
(let loop ([x 1] [y 10])
(loop (+ x 1) (- y 1))
is the same as:
(let ()
(define (loop (x y)
(loop (+ x 1) (- y 1)))
(loop 1 10))
Vectors are O(1) access and indexed so it is a completely different data structure, however you have SEFI-43 which is like the SRFI-1 List library, but for vectors.
#lang racket
(require srfi/43)
(define (min-element lst)
(vector-fold min (vector-ref lst 0) lst))
(max-element #(7 8 1 2 3 4 5 12))
; ==> 1
The racket/vector module has vector-argmin for finding the minimum element of a vector (Well, the minimum after feeding the elements through a transformation function). Combine that with a function like identity from racket/function and it's trivial:
(vector-argmin identity '#(5 4 3 2 1 6))
write a scheme function workit that takes a predicate and a list of integers as arguments. the function should multiply each item in the list that satisfies the predicate by 2 and adds the results. For example::
(workit even? '(1 2 3 4 5 6)) ==> 4+8+12=24
(workit odd? '(1 2 3 4 5 6)) ==> 2+6+10=18
You may not use map, remove, filter, or any other higher order function.
Could someone at least help me get a head start on this? Decided to learn Scheme for a job that I am interested in applying for.... Any help would be great! Thanks
First define even?
(define (even? x) (= 0 (modulo x 2)))
You can define odd? in terms of not even
(define (odd? x) (not (even? x)))
Your workit function is pretty self-explanatory
(define (workit predicate xs)
(define (iter sum xs)
(cond ((empty? xs) sum)
((predicate (first xs)) (iter (+ sum (* 2 (first xs))) (rest xs)))
(else (iter sum (rest xs)))))
(iter 0 xs))
I defined an inner iter function to step through the list of provided numbers, xs, while keeping track of the output, sum.
If the list we're iterating through is empty?, we're done, so return the sum
Else, if (predicate x) is true, add (* 2 x) to the sum and continue iteration
Otherwise, the predicate is false, do not alter the sum for this iteration
I chose to use the auxiliary iter function in order to achieve proper tail recursion. This allows workit to operate in constant space.
Outputs
(print (workit even? '(1 2 3 4 5 6))) ;; => 24
(print (workit odd? '(1 2 3 4 5 6))) ;; => 18
If there are no elements in the list, the workit of the list is some base
value.
If the first element satisfies some condition, then the workit of the list is the result of some operation involving that first element, and the workit of the remainder of the list.
If the first element does not satisfy the condition, then the workit of the list is simply the workit of the remainder of the list.
Note that each time workit is called recursively (as in the second and third cases) the list is the remainder of the list in the the previous call.
So, I'm trying to transform each element of a vector x,in this way: x[i]--> 1-(1/x[i])
(defn change[x]
(fn [i]
(assoc x i (- 1 (/ 1 (get x i))))
)
(range 0 (* (count x) 1))
)
I'm using assoc to replace each element of the vector, I'm supposed to get a vector with the changes, but instead I'm getting a list.
For example
user> (change [21 32 23 34])
(0 1 2 3)
But I should get a vector :v
The code for the function you provided doesn't use the local anonymous function, and can be refactored greatly.
This is your original function with comments.
(defn change[x]
;; start unused anonymous
(fn [i]
(assoc x i (- 1 (/ 1 (get x i)))))
;; end unused anonymous
;; start/end gen list of ints
(range 0 (* (count x) 1)))
This is probably what you mean
(defn change [coll]
(mapv #(- 1 (/ 1 %)) coll))
And this is the output
user> (change [21 32 23 34])
;=> [20/21 31/32 22/23 33/34]
What your code does
Your original code (reformatted)
(defn change [x]
(fn [i] (assoc x i (- 1 (/ 1 (get x i)))))
(range 0 (* (count x) 1)))
evaluates and discards a function value then
returns the range.
So you can omit the fn form and reduce it to
(defn change [x]
(range 0 (* (count x) 1)))
which in turn reduces to
(defn change [x]
(range (count x)))
So, for example,
(change [:whatever :I :choose :to :put :here])
;(0 1 2 3 4 5)
If I have a matrix defined as:
(def m1 [[1 2 3][4 5 6][7 8 9]])
How do I go about counting the vectors within the vector in clojure. I know that (count m1) will return 3 which is the number of vectors I have in the initial vector but I can't remember how to count the inner vectors (its been a very very long time since I've had to deal with any lisp dialect). Also I do not want to flatten the vector and then count it because I need to count the values separately (ie. I want to return 3, 3, 3 because each of the inner vectors have 3 elements. One last restriction I guess is that I want to do this without using map right away because I realized I can simply do (map count m1).
That's actually very simple, just call:
(map count m1)
Or if you want to have your result also in vector:
(mapv count m1)
You'll want to use map. It will apply count to each element in the vector and return a list of counts.
(def m1 [[1 2 3][4 5 6][7 8 9]])
(map count m1)
=> (3 3 3)
Your edit: "I want to do this without using map."
(defn counts [vs]
(loop [vs vs, cs []]
(if (empty? vs)
cs
(recur (rest vs), (conj cs (count (first vs)))))))
One answer quite good but use count. Assume not using count and also not use map
((fn [lst]
(loop [l lst, n 0]
(if (empty? l)
n
(recur (rest l) (inc n)))))'(1 2 3))
For my prime numbers lazy seq, I am checking to see if an index value is divisible by all the primes below that current index (prime?). The problem is, when I call primes within itself (primes within shr-primes line), it only returns the initial value. Is it possible to keep the lazy-seq updated while building it lazily? It seems counter-intuitive to the lazy-seq concept.
(def primes
(cons 2 (for [x (range)
:let [y (-> x (* 2) (+ 3))
root (math/floor (math/sqrt y))
shr-primes (take-while (partial >= root) primes) ;; primes stuck at init value
prime? (every? #(not= % 0) (pmap #(rem y %) shr-primes))]
:when prime?]
y)))
If you're doing the Project Euler problems, I don't want to spoil the exercise for you, but here's how you would define a Fibonacci sequence so that the lazy-seq keeps "updating" itself as it goes:
(defn fib-maker
([] (concat [0 1] (fib 0 1)))
([a b] (lazy-seq (cons b (fib b (+ a b))))))
(def fib (fib-maker))
I've used the above approach to implement the prime number sequence you've outlined above, so if you want more details let me know. Meanwhile, this will hopefully be a helpful hint.