Settings

Theme

Show HN: An Experimental 'LINQ to Objects' in Go

github.com

1 points by suzuki 7 years ago · 1 comment

Reader

suzukiOP 7 years ago

This LINQ implementation is unique in that it is not related to any particular data structure.

The LINQ code in C# found at https://docs.microsoft.com/dotnet/api/system.linq.enumerable... can be written in Go with this implementation as follows:

  // Generate a sequence of integers from 1 to 10 and then select their squares.
  squares := Range(1, 10).Select(func(x Any) Any { return x.(int) * x.(int) })
  squares(func(num Any) {
      fmt.Println(num)
  })
Here the function Range is defined as follows:

  // Range creates an Enumerator which counts from start
  // up to start + count - 1.
  func Range(start, count int) Enumerator {
      end := start + count
      return func(yield func(Any)) {
          for i := start; i < end; i++ {
              yield(i)
          }
      }
  }
Note that Enumerator is just a function type defined as func(func(Any)). The space complexity is O(1) and you can yield values infinitely if you want.

Keyboard Shortcuts

j
Next item
k
Previous item
o / Enter
Open selected item
?
Show this help
Esc
Close modal / clear selection