-1

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.

Harsh Shah
  • 368
  • 3
  • 17

4 Answers4

1

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) )
    )
Shawn Zhang
  • 1,680
  • 1
  • 12
  • 21
1

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.

markg
  • 23
  • 5
1

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)))
Diego Basch
  • 12,764
  • 2
  • 29
  • 24
0

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)
Thumbnail
  • 13,293
  • 2
  • 29
  • 37
  • wouldnt loop/recur count as recursion, since internally the compiler converts it to recursion? – Harsh Shah Sep 11 '14 at 23:51
  • @HarshShah I think it's the other way round:`recur` is a recursive *construct* that the compiler translates into a loop. [The official docs](http://clojure.org/special_forms#Special%20Forms--(recur%20exprs*)) describe its action as a *jump*. – Thumbnail Sep 12 '14 at 07:01