Skip to content

Instantly share code, notes, and snippets.

@Xliff
Last active September 21, 2019 05:07
Show Gist options
  • Save Xliff/9fb038df877e72df52196bc6bf8be7e8 to your computer and use it in GitHub Desktop.
Save Xliff/9fb038df877e72df52196bc6bf8be7e8 to your computer and use it in GitHub Desktop.
Why go with Go?

Take this example

package sort_test

import (
    "fmt"
    "sort"
)

type Person struct {
    Name string
    Age  int
}

func (p Person) String() string {
    return fmt.Sprintf("%s: %d", p.Name, p.Age)
}

// ByAge implements sort.Interface for []Person based on
// the Age field.
type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }

func Example() {
    people := []Person{
        {"Bob", 31},
        {"John", 42},
        {"Michael", 17},
        {"Jenny", 26},
    }

    fmt.Println(people)
    sort.Sort(ByAge(people))
    fmt.Println(people)

    // Output:
    // [Bob: 31 John: 42 Michael: 17 Jenny: 26]
    // [Michael: 17 Jenny: 26 Bob: 31 John: 42]
}

Here's the equivalent Perl6:

my class Person {
  has $.name;
  has $.age;

  method gist {
    "{ $.name }: { $.age }";
  }
}
  
my @ppl = (
  Person.new( name => "Bob", age => 31),
  Person.new( name => "John", age => 42),
  Person.new( name => "Michael", age => 17),
  Person.new( name => "Jenny", age => 26)
);
  
.say for @ppl;
say '';
.say for @ppl.sort( *.age );

And the output:

Bob: 31
John: 42
Michael: 17
Jenny: 26

Michael: 17
Jenny: 26
Bob: 31
John: 42

Now there are obvious advantages to Go, namely speed and scalability. However simplicity has its place, and Perl6 beats Go, hands down. Also, the performance and scalability of the Perl6 solution are not that bad in comparison.

I entreat that when the language is easy to write in, then everyone benefits.

So far, I haven't seen anything from Python, Go, Rust or any of the other contenders that beats Perl6 in that regard.

@Xliff
Copy link
Author

Xliff commented Sep 21, 2019

And if you want to strip it to the bare bones, then:

my class Person {
  has $.name;
  has $.age;

  method gist {
    "{ $.name }: { $.age }";
  }
  
  method new ($name, $age) {
    self.bless(:$name, :$age);
  }
}

my @ppl;
@ppl.push: Person.new(|$_) for (
  [ "Bob", 31 ],
  [ "John", 42 ],
  [ "Michael", 17 ],
  [ "Jenny", 26 ]
);
  
.say for @ppl;
say '';
.say for @ppl.sort( *.age );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment