Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping over sequence with a constant

If I need to provide a constant value to a function which I am mapping to the items of a sequence, is there a better way than what I'm doing at present:

(map my-function my-sequence (cycle [my-constant-value]))

where my-constant-value is a constant in the sense that it's going to be the same for the mappings over my-sequence, although it may be itself a result of some function further out. I get the feeling that later I'll look at what I'm asking here and think it's a silly question because if I structured my code differently it wouldn't be a problem, but well there it is!

like image 757
Hendekagon Avatar asked Mar 04 '11 05:03

Hendekagon


2 Answers

In your case I would use an anonymous function:

(map #(my-function % my-constant-value) my-sequence)

Using a partially applied function is another option, but it doesn't make much sense in this particular scenario:

(map (partial my-function my-constant-value) my-sequence)

You would (maybe?) need to redefine my-function to take the constant value as the first argument, and you don't have any need to accept a variable number of arguments so using partial doesn't buy you anything.

like image 52
dbyrne Avatar answered Oct 07 '22 06:10

dbyrne


I'd tend to use partial or an anonymous function as dbyrne suggests, but another tool to be aware of is repeat, which returns an infinite sequence of whatever value you want:

(map + (range 4) (repeat 10))
=> (10 11 12 13)
like image 29
amalloy Avatar answered Oct 07 '22 08:10

amalloy