适用于具有各种数据字段的用户的功能 [英] Function for applying to a user with a various number of data fields
问题描述
当我练习教程
我正在尝试将该功能应用于用户,但无法使用用户的数据字段(例如姓名,姓氏)。
The question was born when I was practicing an Observer topic in a tutorial I am trying to apply the function to the user but cannot use user's data fields like name, surname.
假设用户可能具有不同数量的数据字段,因此我们必须使用& args
参数。我的代码无效:
Let's say that the user may have various number of data fields so we must use & args
argument. My code that does not work:
(ns observer.core)
(def user {:name "Alan" :surname "Smith" :alias "Mike"})
(def user2 {:name "Jane" :surname "Smith"})
(apply
(fn [& args] (println (str "I am " (:name args) " " (:surname args) ".")))
user)
(apply
(fn [& args] (println (str "My sister is " (:name args) " " (:surname args) ".")))
user2)
输出:
I am .
My sister is .
observer.core>
如何解决应用
推荐答案
apply
将映射转换为seq ,即
{:name Alan:surname Smith:alias Mike}
变成([:name Alan ] [:姓氏 Smith] [:别名 Mike])
apply
converts a map to a seq, i.e.
{:name "Alan" :surname "Smith" :alias "Mike"}
becomes ([:name "Alan"] [:surname "Smith"] [:alias "Mike"])
如果可以,可以将其放回地图中您需要什么:
You could put it back into a map, if that is what you need:
(let [user {:name "Alan" :surname "Smith" :alias "Mike"}]
(apply
(fn [& args]
(let [args (into {} args)]
(println (str "I am " (:name args) " " (:surname args) "."))))
user))
但是这对我来说似乎有点困难。我相信,如果我知道应该如何使用此功能,解决方案可能会更好。
but this looks a bit of a stretch to me. I believe the solution could have been better if I knew how this function is supposed to be used.
通常有两种类型的功能:( fn:text some:row 25)
和(fn {:text some:row 25})
。
Usually there are two types of functions: (fn :text "some" :row 25)
and (fn {:text "some" :row 25})
.
这篇关于适用于具有各种数据字段的用户的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!