Last active
May 29, 2016 03:47
-
-
Save akitaonrails/0d4a9a719e78ec5c61916b4f129e2d95 to your computer and use it in GitHub Desktop.
Go to Crystal: Concurrency Tour #2 (https://tour.golang.org/concurrency/2)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} |
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
@akitaonrails Nice! But I'd say this is more idiomatic Crystal (no need for
main
, can usespawn
without a block, like in Go):Or maybe even this (type annotations are not required in arguments):