Skip to content

Instantly share code, notes, and snippets.

@akitaonrails
Last active May 29, 2016 03:47
Show Gist options
  • Save akitaonrails/0d4a9a719e78ec5c61916b4f129e2d95 to your computer and use it in GitHub Desktop.
Save akitaonrails/0d4a9a719e78ec5c61916b4f129e2d95 to your computer and use it in GitHub Desktop.
Go to Crystal: Concurrency Tour #2 (https://tour.golang.org/concurrency/2)
def sum(s : Array(Int32), c : Channel(Int32))
c.send s.reduce(0) { |sum, v| sum + v }
end
def main
s = [7, 2, 8, -9, 4, 0]
c = Channel(Int32).new
spawn {
sum(s[0..((s.size / 2) - 1)], c)
}
spawn {
sum(s[(s.size / 2)..-1], c)
}
x, y = c.receive, c.receive
puts "x, y = #{x}, #{y}"
end
main
package main
import "fmt"
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
@akitaonrails
Copy link
Author

Great, I agree, I was just doing a 1 to 1 translation just to show the difference but your version is definitely better.

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