what does (seq) in zipmap do?

瀏覽次數:99 次
跳到第一則未讀訊息

larry google groups

未讀,
2016年11月29日 晚上10:42:482016/11/29
收件者:Clojure
I apologize for this question, because I think it has been asked before, and yet I can not find the answer. 

In the definition of zipmap, what do these 2 lines do?

ks (seq keys)
vs (seq vals)

In particular, what is (seq) doing? Is this to ensure that ks is false if "keys" is empty? And vs is false if "vals" is empty? Because an empty list (or vector) is truthy but we want it to be falsey in this situation?  

Is there any other reason to use (seq), other than to set the truthy/falsey values of ks and vs? 


(defn zipmap
"Returns a map with the keys mapped to the corresponding vals."
{:added "1.0"
:static true}
[keys vals]
(loop [map {}
ks (seq keys)
vs (seq vals)]
(if (and ks vs)
(recur (assoc map (first ks) (first vs))
(next ks)
(next vs))
map)))

Andy Fingerhut

未讀,
2016年11月30日 凌晨2:08:092016/11/30
收件者:clo...@googlegroups.com
I can't answer for the author, but the answer you gave would be a good sufficient reason to call seq in those places, yes?

If you create a function zipmap2 that is identical to zipmap, except it does not have any calls to seq, you get these results:

user=> (zipmap [] [1])

{}

user=> (zipmap2 [] [1])

{nil 1}


I definitely think the former result makes more sense than the latter does.

If you are thinking that it would be better to have the calls to seq in the if condition, that would be at least a little bit slower than the current implementation, as it would have 2 additional calls to seq for every iteration through the loop.

Andy


--
You received this message because you are subscribed to the Google
Groups "Clojure" group.
To post to this group, send email to clo...@googlegroups.com
Note that posts from new members are moderated - please be patient with your first post.
To unsubscribe from this group, send email to
clojure+unsubscribe@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/clojure?hl=en
---
You received this message because you are subscribed to the Google Groups "Clojure" group.
To unsubscribe from this group and stop receiving emails from it, send an email to clojure+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Alex Miller

未讀,
2016年11月30日 上午8:15:492016/11/30
收件者:Clojure
keys and vals could be any kind of collection. Calling seq will return either nil or a seq with at least one value. By forcing empty collections to nil allows the (and ks vs) to work.

That is if keys is [] and vals is [1], then:

(and keys vals) is [1] (a truthy value)

But (seq []) is nil and (seq [1]) is (1) and (and nil (1)) is nil (a falsey value).

There are a lot of ways zipmap's performance can be improved (particularly if keys and vals are reducible) and there is a ticket where some ideas have been discussed: http://dev.clojure.org/jira/browse/CLJ-1005
回覆所有人
回覆作者
轉寄
0 則新訊息