clojure - 使用函数内的部分作为地图上的值
问题描述
首先; 抱歉,如果我使用的术语不正确,我对 clojure 还是很陌生,范式转变需要一些时间。
我正在尝试使用一个函数,该函数从大于十二的集合中获取第一个项目(是一个“青少年”数字)。当我只是将它直接应用到集合时,我可以写这个,但我不确定如何在地图中编写函数。谁能指出我正确的方向?
我尝试了一些事情,通常沿着(partial (first (filter (partial < 12))))
但到目前为止没有任何运气,并且研究过滤器/部分的定义尚未证明是富有成果的。
TL/DR 我想要一个函数,作为地图中的一个值,它采用大于 12 的列表中的第一项。
(def test-set [1, 8, 15, 22, 29])
(def some-functions {
:first first
:last last
:teenth "I don't know what to put here"
})
(first (filter (partial < 12) test-set))
解决方案
一种方法是在定义地图时使用匿名函数(https://riptutorial.com/clojure/example/15544/defining-anonymous-functions)
> (def some-functions {
:first first
:last last
:teenth #(first (filter (partial < 12) %))})
> ((:first some-functions) test-set)
1
> ((:last some-functions) test-set)
29
> ((:teenth some-functions) test-set)
15
当然你也可以明确定义你的函数并在你的地图中使用它:
> (defn teenth [coll] (first (filter (partial < 12) coll)))
> (def some-functions {
:first first
:last last
:teenth teenth})
(顺便说一句,要小心这个词set
。在 clojure 中,集合是唯一值的无序集合。https://clojure.org/reference/data_structures)
推荐阅读
- excel - 如何在 Excel VBA 中使用带有变量而不是单元格引用的字符对象
- python - 安装 Mysql 并连接到 Django 时出错
- reactjs - 如何设置条件渲染navlink
- python-3.x - 我正在尝试从whatsapp web 下载一些图片
- linux - 如何使用 Bash 将命令输出列表变成菜单选项列表?
- linux - 将更改推送到我自己的远程存储库时出错(身份验证问题)
- javascript - ionic:如何允许多个菜单?
- r - R:在函数中使用 smooth.spline
- javascript - 如何使用 AJAX 将 PHP 数组传递给 HTML 页面?
- python - “从不太安全的应用程序访问”的解决方法