Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to apply a function to each element of a list or vector in Clojure

I see that the map function exists in Clojure, but I don't understand how to refer to each element in the list. Not sure if it is possible. In Ruby, I would write something like this:

list_of_numbers = [1,2,3]
list_of_numbers.map {|num| num * 2}

can I do something like that with the map function in Clojure?

like image 531
Corey Avatar asked Nov 17 '25 10:11

Corey


1 Answers

(def nums [1 2 3])
(def doubles (mapv #(* % 2) nums))   ; or just `map`
(println doubles)

=> [2 4 6]

For a good start, see:

  • http://braveclojure.com
  • Clojure CheatSheet
  • books like Getting Clojure
  • http://clojure.org
like image 139
Alan Thompson Avatar answered Nov 20 '25 05:11

Alan Thompson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!