#Anonymous function for range - hash set library

12 messages · Page 1 of 1 (latest)

raw bridge
#

Greetings,

I am using this library https://github.com/G-M-twostay/Go-Utils/blob/master/Sets/HashSet/HashSet.go.
I am confused by the range function (https://github.com/G-M-twostay/Go-Utils/blob/de5fd5dbdbfd46f9e77cce13823929a74293d844/Sets/HashSet/HashSet.go#L191)

My question is: what would be the anonymous function inside of Range?

func (u *HashSet[E]) Range(f func(E) bool) {
GitHub

Some parallel and less known but good data structure - Go-Utils/HashSet.go at de5fd5dbdbfd46f9e77cce13823929a74293d844 · G-M-twostay/Go-Utils

ebon heart
#

" what would be " like what the function should do ? or what the function should looks like?

#

Range will iterate over each item in the set and call function f on each item.
when f return false, range stop. instead of iterating over the rest of the item in the set.

#

think about forEach array function in js, except you can determine, when to stop or continue.

raw bridge
#

" what would be " like what the function should do ? or what the function should looks like?
What the function should look like.

The name suggests it's used to range through the hash set but I can't figure out "what" to write as anonymous function. I don't see any iterator and I can't have access to any.

ebon heart
raw bridge
ebon heart
#

you passed a callback f to Range and it'll call f on each item, passed as argument.
f return bool to tell Range, to continue or stop.
about what you do with each item, its up to you.

raw bridge
#

If I want to print the elements, I should make a function like the following?

foo.Range(func(i int) bool {
        if foo.Has(i) {
            fmt.Println(i)
            return true
        } else {
            return false
        }
    })

Where foo is my previously declared hash set.

ebon heart
#
foo.Range(func(i int) bool {
        fmt.Println(i)
        return true
    })
raw bridge
#

This is the first time I am seeing this kind of function.
Thank you very much for your help!

ebon heart
#

its similar to filepath.Walk, but filepath.WalkFunc return an error to tell filepath to stop, instead of boolean.