How to get a single element in a set containing one element

I have a collection containing one element, in this case a line:

b = Set(["A"]) 

I want to get this single item. What is the best way to do this? The only way I can figure this out is to use a loop:

 single_item = "" for item in b single_item = item end 

which gets mine what i need

 julia> single_item "A" 

but I feel that there should be an easier way.

+5
source share
2 answers

I suggest first

 julia> b = Set(["A"]) Set(ASCIIString["A"]) julia> first(b) "A" 

We can talk about this by looking at the number of distributions. (since memory allocation is slow). I would ignore the actual time, as this is one run. The results shown are the second run of each call. with b declared const .

 julia> @time first(b) 0.000003 seconds (4 allocations: 160 bytes) "A" julia> @time collect(b)[1] 0.000005 seconds (5 allocations: 240 bytes) "A" julia> @time first(next(b,start(b))) 0.000007 seconds (5 allocations: 192 bytes) "A" 
+5
source

What about

 julia> collect(b)[1] "A" 

change

as the legendary Dan Goetz suggested, consider making

 julia> collect(take(b,1))[1] "A" 

if memory problem

+6
source

Source: https://habr.com/ru/post/1259494/


All Articles