Anonymous function returning 1 using #()

大兔子大兔子 提交于 2019-12-20 17:37:34

问题


Using defn or fn it's easy to create a function that taking one argument that ignores it and returns 1:

(defn ret1 [arg] 1)
(fn [arg] 1)

Is it possible to do this with the #() macro? I don't mean using something ugly or "cheating" like

#(/ % %)  or 
#(if (nil? %) 1 1)

I mean literally ignoring the parameter and returning 1. I can't find a clean syntax that works.


回答1:


#(do %& 1) ... but (constantly 1) is better.




回答2:


The #() syntax can't be used to create functions that have unused parameters in the way your description requires. This is a limitation of the #() reader macro.

I would recommend not using #() and instead just writing (constantly 1) which is a very brief way to create a function that ignores a parameter and instead always returns 1.




回答3:


How about #(identity 1)? which does the same thing as #(do %& 1) or (constantly 1).



来源:https://stackoverflow.com/questions/5005437/anonymous-function-returning-1-using

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!