Pregunta

I'm hitting some kind of mental roadblock related to destructuring...

(sorted-set 4 2 5)

gives:

#{2 4 5}

But How I can get that same sorted set from:

((fn [???] (sorted-set ???)) [4 2 5])

or from a set (unsorted) passed as an argument:

((fn [???] (sorted-set ???)) #{4 2 5})  

I tried several destructuring, I was thinking that:

((fn [#{elems}] (sorted-set elems)) #{4 2 5})

would work but this is not the case.

I'd like to know how to do that and it would be even better if you could explain why my way of reasoning is bogus...

¿Fue útil?

Solución

the sorted-set function param is a var-arg: [& keys], which means that if you have a collection and you want to call that function you need to use the apply function like:

user=> (def v [4 8 2])
#'user/v
user=> (apply sorted-set v)
#{2 4 8}

The signature of a function that accepts a collection and returns a sorted-set would be like:

user=> (defn to-ss [c] (apply sorted-set c))
#'user/to-ss
user=> (to-ss v)
#{2 4 8}

You could also create an empty sorted-set and then add all the elements of the collection to it:

(defn to-ss [c] (into (sorted-set) c))

Note that if you were to define your function with a var-arg parameter, you will need to use apply to both call the function and create the sorted-set:

user=> (defn to-ss [& items] (apply sorted-set items))
#'user/to-ss
user=> (apply to-ss v)
#{2 4 8} <-- expected value
user=> (to-ss v)
#{[4 8 2]} <-- sorted-set with just one value
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top