Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a reverse-map function?

Tags:

clojure

In clojure you can map a function to a sequences of values. Is there an inbuilt function to map a single value as parameter to a sequence of functions?

(map inc [1 2 3 4])
; -> (2 3 4 5)

(reverse-map [inc dec str] 1)
; -> (2 0 "1")

(reverse-map [str namespace name] :foo/bar/baz)
; -> (":foo/bar/baz" "foo/bar" "baz")
like image 540
AnnanFay Avatar asked Dec 05 '22 17:12

AnnanFay


2 Answers

There's juxt which is a bit similar. It takes a number of functions and returns one that passes its argument(s) to each of the functions and returns a vector of return values. So:

> ((apply juxt [inc dec str]) 1)
[2 0 "1"]

The main difference is that it creates a vector, which is of course eager (i.e. not lazy.) The original map creates a sequence which is lazy.

juxt also works on functions that have more than 1 argument:

> ((apply juxt [* / -]) 6 2)
[12 3 4]
like image 79
Rafał Dowgird Avatar answered Jan 13 '23 17:01

Rafał Dowgird


Not sure if there is one, but it's fairly easy to implement:

(def reverse-map (fn [l value] (map #(% value) l)))
like image 43
soulcheck Avatar answered Jan 13 '23 18:01

soulcheck