【问题标题】:Clojure - How to put a list and a function inside a defn functionClojure - 如何将列表和函数放入 defn 函数中
【发布时间】:2019-11-14 13:20:07
【问题描述】:

我是新手,正在做一些练习。如何在 defn 函数中放置带有句子列表和随机化函数的 def?这是如何运作的?

(def list["test1", "test2", "test3"]) - 工作正常 (rand-nth list) - 工作正常

如何将它放在函数defn 中?

感谢您的帮助。

【问题讨论】:

  • 我会说,使用let,但真的不是很清楚,你所说的“放入defn”是什么意思。您能否添加您尝试过的内容以及失败的原因?

标签: function clojure defn


【解决方案1】:

IIUC 你只是想重新实现rand-nth,不是吗?

(defn wrapped-rand-nth [a-list]
  (rand-nth a-list))

如果您希望列表是静态的(不变的)

(defn randomize []
  (rand-nth ["test1" "test2" "test3"]))

有效,但它会在每次调用时创建向量,更好的方法是

(let [the-list ["test1" "test2" "test3"]]
  (defn randomize []
    (rand-nth the-list)))

【讨论】:

  • 太好了,这正是我想要的——第二个选项。谢谢你 。 :)
猜你喜欢
  • 2017-10-09
  • 1970-01-01
  • 1970-01-01
  • 2013-11-15
  • 2011-05-26
  • 1970-01-01
  • 1970-01-01
  • 2018-12-19
  • 2017-10-12
相关资源
最近更新 更多