News for hackers. Stuff that matters.
Re:Golang Diaries II by cmccabe on Tuesday July 16, 2013 @01:50AM (#6050217)
That's not necessary. You can just create a type that embeds the type you're sorting, and define the Less function however you like. It's very efficient since you're just wrapping the entire slice object, not every element in the slice.

  package main
  import "sort"
  type RevIntSlice struct {
      sort.IntSlice
  }
  func (arr RevIntSlice) Less(i, j int) bool {
      return arr.IntSlice.Less(j, i)
  }
  func main() {
    myList := RevIntSlice { sort.IntSlice {1, 2 , 3 } }
    sort.Sort(myList)
    for _, elem := range(myList.IntSlice) {
        println(elem)
    }
  }
Note that if all you want to do is reverse the sort order, sort.Reverse is a better way than what I wrote here. This is just an example of the kinds of things you can do.
Re:Golang Diaries II by chongli on Tuesday July 16, 2013 @05:59AM (#6050830)
>That's not necessary. You can just create a type that embeds the type you're sorting

But that's more work (and more boilerplate) than simply passing an anonymous comparator to the sort function.

Re:Golang Diaries II by cmccabe on Wednesday July 17, 2013 @04:04AM (#6056639)
Let me guess. You are coming from Java. In Java this would be:

  myArray.sort(new Comparator<MyClass> ({
    @Override
    CompareTo(MyClass lhs, MyClass rhs) {
      return rhs.compare(lhs);
    }
  }));
Is that really shorter? I don't think so.

In any case, there is a more elegant solution in Go, which is simply:

  sort.Sort(sort.Reverse(array))
You need to open your mind a little bit, to learn a new language.
Re:Golang Diaries II by chongli on Wednesday July 17, 2013 @02:28PM (#6059315)
You are coming from Java.

Nope. Clojure and Haskell. Clojure:

    user=> (sort > (vals {:foo 5, :bar 2, :baz 10}))
    (10 5 2)
Haskell:

    >>> sortBy (flip compare) . map snd $ [("foo", 5), ("bar", 2), ("baz", 10)]
    [10,5,2]
Re:Golang Diaries II by jlujan on Tuesday July 16, 2013 @04:53PM (#6054679)
Yes. I am aware how to sort and can only read your comment as as informative sarcasm as to the ease.