Skip to content

Instantly share code, notes, and snippets.

@SimonRichardson
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save SimonRichardson/653f4d55acaae7f11fb2 to your computer and use it in GitHub Desktop.

Select an option

Save SimonRichardson/653f4d55acaae7f11fb2 to your computer and use it in GitHub Desktop.
product
// You can edit this code!
// Click here and start typing.
package main
import "fmt"
type AnyVal interface{}
type IProduct interface {
ProductArity() int
ProductElement(index int) AnyVal
ProductPrefix() string
MkString(separator string) string
}
type Product struct {
arity int
element func(index int) AnyVal
}
func NewProduct(x []AnyVal) Product {
return Product{
arity: len(x),
element: func(index int) AnyVal {
return x[index]
},
}
}
func (p Product) ProductArity() int {
return p.arity
}
func (p Product) ProductElement(index int) AnyVal {
return p.element(index)
}
func (p Product) ProductPrefix() string {
return ""
}
func (p Product) MkString(separator string) string {
n := p.ProductArity()
m := n - 1
var rec func(buffer, sep string, index int) string
rec = func(buffer, sep string, index int) string {
if index >= n {
return buffer
}
var s string
if index != m {
s = sep
} else {
s = ""
}
return rec(fmt.Sprintf("%s%v%s", buffer, p.ProductElement(index), s), sep, index+1)
}
return rec("", separator, 0)
}
func (p Product) validateIndex(index int) error {
return requireRange(index, p.ProductArity())
}
func requireRange(index, end int) error {
if index < 0 || index > end {
return fmt.Errorf("Index %d is out of range.", index)
}
return nil
}
type Option interface {
}
type Some struct {
Product
}
func NewSome(x AnyVal) Some {
return Some{
NewProduct([]AnyVal{x}),
}
}
func main() {
p := NewProduct([]AnyVal{1, 2})
fmt.Println(p.ProductArity())
fmt.Println(p.MkString(", "))
fmt.Println(p.validateIndex(10))
o := NewSome(2)
fmt.Println(o.ProductArity())
fmt.Println(o.MkString(", "))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment