Fragment Description:



Checking the unicity of members in a collection.
Using a 'map' and its 'seenit/ok/exist' idiom, along with goroutine and channel.
A channels embrace...
for fun.


isItUnique

Go Playground

Last update, on 2015, Fri 9 Oct, 16:15:29

/* ... <== see fragment description ... */

package main

import (
    "fmt"
)

type empty struct{}

func makeIsUniq() func(s string) bool {
    ch := make(chan string)
    uniq := make(chan bool)
    seen := make(map[string]empty)
    go func() {
        // ready to receive s
        for s := range ch {
            seenit := false
            // the seenit idiom
            if _, seenit = seen[s]; !seenit {
                // not found -- add it, not really
                seen[s] = empty{}
            }
            // sending the answer
            uniq <- !seenit
        }
    }()
    // why not?
    return func(s string) bool {
        // sending s
        ch <- s
        // ready to receive the answer
        return <-uniq
    }
}
func main() {
    isUniq := makeIsUniq()
    items := []string{"a", "b", "c", "b", "a", "d", "d"}
    for i, s := range items {
        fmt.Println("pass:", i, "\tvalue:", s, ",\tis it unique?\t", isUniq(s))
    }
}

/* Expected Output:
pass: 0    value: a ,  is it unique?    true
pass: 1    value: b ,  is it unique?    true
pass: 2    value: c ,  is it unique?    true
pass: 3    value: b ,  is it unique?    false
pass: 4    value: a ,  is it unique?    false
pass: 5    value: d ,  is it unique?    true
pass: 6    value: d ,  is it unique?    false
*/



Comments