Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does this one line of Clojure code do?

(map #(words %) indexes)

words is a vector of strings and indexes is a sequence of non-negative integers. I understand that #(...) is an anonymous function and % represents the arguments to it. I think the idea is to get words at the specified indexes but can someone please rewrite the anonymous function into a function that's easier to understand?

like image 682
user1136342 Avatar asked Sep 13 '26 20:09

user1136342


2 Answers

This is just a bad way to write (map words indexes). I don't know what the function words does, or what the value of indexes is, but this code calls the function words once on each element of indexes and returns a sequence of the results.

like image 93
amalloy Avatar answered Sep 16 '26 23:09

amalloy


If I understand correctly you have:

(def words ["who" "what" "where" "when"])
(def indexes (range 4))
(map #(words %) indexes)
    => ("who" "what" "where" "when")

One of the nice things about clojure is that the standard data structures are also functions of their members. This means the following are equivalent:

(get words 1)
  => "what"
(words 1)
   =>"what"

This also works for maps and sets. The former takes a key and returns the value. The latter looks for the argument in the list and returns it if found or nil.

like image 35
M Smith Avatar answered Sep 17 '26 01:09

M Smith