首页 > 解决方案 > 使用函数内的部分作为地图上的值

问题描述

首先; 抱歉,如果我使用的术语不正确,我对 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))

标签: clojure

解决方案


一种方法是在定义地图时使用匿名函数(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


推荐阅读