用常量映射序列
如果我需要为映射到序列项的函数提供一个常量值,有没有比我目前正在做的更好的方法:
(map my-function my-sequence (cycle [my-constant-value]))
其中 my-constant-value 是一个常量,因为它是my-sequence 上的映射将是相同的,尽管它本身可能是某些更远的函数的结果。我感觉稍后我会看看我在这里问的问题,并认为这是一个愚蠢的问题,因为如果我以不同的方式构建我的代码,那不会是一个问题,但事实就是如此!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在您的情况下,我将使用匿名函数:
使用部分应用的函数是另一种选择,但在这种特定情况下没有多大意义:
您(也许?)需要重新定义 my-function 以将常量值设为第一个参数,并且您不需要接受可变数量的参数,因此使用
partial
不会给您带来任何好处。In your case I would use an anonymous function:
Using a partially applied function is another option, but it doesn't make much sense in this particular scenario:
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.我倾向于使用部分或匿名函数,如 dbyrne 建议的那样,但另一个需要注意的工具是
repeat
,它返回一个无限序列,无论你想要什么值: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
更具可读性的另一种方法是for
列表理解宏:Yet another way that I find sometimes more readable than
map
is thefor
list comprehension macro:是的:)来自 API 的“其他有用的函数” 部分的小宝石
不断
(map my-function my-sequence (constantly my-constant-value))(map compines-data Something-new a-constant) 的模式在 idomatic clojure 中相当常见。对于分块序列等,它也相对较快。
编辑:这个答案是错误的,但是
constantly
和其余的“其他有用的函数”api 非常酷,无论如何我想将这里的引用留给他们。yep :) a little gem from the "other useful functions" section of the api
constantly
(map my-function my-sequence (constantly my-constant-value))the pattern of (map compines-data something-new a-constant) is rather common in idomatic clojure. its relativly fast also with chunked sequences and such.
EDIT: this answer is wrong, but
constantly
and the rest of the "other useful functions" api are so cool i would like to leave the reference here to them anyway.