Skip to content

Instantly share code, notes, and snippets.

@logicalguess
Created October 18, 2017 03:13
Show Gist options
  • Save logicalguess/43f571d92854ed6f2fec53d1964a7eea to your computer and use it in GitHub Desktop.
Save logicalguess/43f571d92854ed6f2fec53d1964a7eea to your computer and use it in GitHub Desktop.
Input processing logic as a partial function in Go.
package main
import (
"fmt"
"errors"
)
type G interface{}
type X struct {
active bool
}
type Y struct {
active bool
}
type _T interface {
_T()
}
func (x X) _T() {}
func (y Y) _T() {}
type T struct {
X
Y
}
func encode(g G) T {
switch g.(type) {
case X:
x := g.(X)
x.active = true
return T{X: x, Y: Y{}}
case Y:
y := g.(Y)
y.active = true
return T{X: X{}, Y: y}
default:
return T{}
}
}
func decode(t T) _T {
var i _T
if t.X.active {
if t.Y.active {panic("invalid input")}
i = t.X
} else
if t.Y.active {
i = t.Y
} else {
panic("unknown type")
}
return i
}
func logic(i _T) G {
switch i.(type) {
case X:
return i.(X)
case Y:
return i.(Y)
default:
return errors.New("sorry, can't do")
}
}
func main() {
receive := func(t T) G {
i := decode(t)
return logic(i)
}
fmt.Printf("logic type %T\n", logic(X{}))
fmt.Printf("logic type %T\n", logic(Y{}))
fmt.Printf("receive type %T\n", receive(encode(X{})))
fmt.Printf("receive type %T\n", receive(encode(Y{})))
//fmt.Printf("type %T\n", f(T{}))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment