Matt Y.
Matt Y.

Reputation: 49

Sequentially calling a function with elements from a vector

Suppose I have a function f that accepts two arguments x & y. I also have a vector X composed of elements x1, x2, ... xn.

How can I write a function g, where g(X, y) calls f(xi, y) for all x?

Further specification: I would like g to return a vector, where each element stores the result of f(xi, y). My understanding is that I should be considering map or mapv.

Upvotes: 0

Views: 93

Answers (3)

andih
andih

Reputation: 5603

You can use map to implement it.

I'm using a lambda expression here to define a function which takes only one argument.

(defn f [x y ] (...) )
// apply f x y to every element of xs 
// in order to do this we need a function which takes only one argument the x_i and takes the second argument from somehere else - the second argument of g 
// that's what the lambda \x -> f x y does - in short form.
(defn g [xs y] (map (fn [x] (f x y)) xs))

for example

(def X [1 2 3 4])
(defn f [x y] (* x y))
(g X 3)
;=> (3 6 9 12)

Upvotes: 2

Mars
Mars

Reputation: 8854

If you can rearrange the definition of f so that y is the first parameter, you can do it this way:

(defn f [y x] ...)
(map (partial f y) xs)

partial returns a function in which y is "baked in" as the first argument to f. For functions that take more than two arguments, you can pass additional arguments to partial, and the returned function will accept arguments for whatever parameters are still unfilled.

Upvotes: 1

Alan Thompson
Alan Thompson

Reputation: 29958

Here is a simple way using for:

(def y 5)
(def xx (range 5))  ;=> [0 1 2 3 4]
(defn ff [x y] (+ y (* x x)))
(defn gg [xx y] (for [x xx] (ff x y)))
(gg xx y)
;=> (5 6 9 14 21)

You could also use repeat:

(defn g2 [xx y] (mapv ff xx (repeat y)))
(g2 xx y)
;=> [5 6 9 14 21]

Upvotes: 0

Related Questions