Skip to content

Instantly share code, notes, and snippets.

@riking
Created March 17, 2017 07:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riking/b3a2f8df7c8d27ca1d6d925a06e5cc88 to your computer and use it in GitHub Desktop.
Save riking/b3a2f8df7c8d27ca1d6d925a06e5cc88 to your computer and use it in GitHub Desktop.
Acing the Technical Interview in #golang https://aphyr.com/posts/340-acing-the-technical-interview
package list
import (
"fmt"
"io"
)
// generics - swap out V1 for a new implementation
type V1 int32
type I1 interface {
Get() V1
Next() I1
}
type T1 V1
type N1 func(bool) I1
func (t T1) Get() V1 { return V1(t) }
func (t T1) Next() I1 { return nil }
func (l N1) Get() V1 { return l(true).Get() }
func (l N1) Next() I1 { return l(false) }
var e I1
func Cons(h, t I1) N1 {
return func(q bool) I1 {
if q {
return h
}
return t
}
}
func Nth(l I1, n int) V1 {
switch n {
case 0:
return l.Get()
default:
return Nth(l.Next(), n-1)
}
}
func Print(l I1, w io.Writer) {
fmt.Fprint(w, "(")
for l != e {
fmt.Fprint(w, l.Get())
l = l.Next()
if l != e {
fmt.Fprint(w, " ")
}
}
fmt.Fprint(w, ")")
}
func Reverse(l I1) I1 {
return reverse(e, l)
}
func reverse(r, l I1) I1 {
if l == e {
return r
}
return reverse(Cons(T1(l.Get()), r), l.Next())
}
package list_test
import "fmt"
import (
"localhost.localdomain/list"
"os"
)
func ExampleCons() {
l := list.Cons(list.T1(1), list.Cons(list.T1(2), nil))
fmt.Println(l.Get())
fmt.Println(l.Next().Get())
// Output:
// 1
// 2
}
func ExampleNth() {
l := list.Cons(list.T1(1), list.Cons(list.T1(2), nil))
l = list.Cons(list.T1(3), l)
fmt.Println(list.Nth(l, 1))
fmt.Println(list.Nth(l, 2))
// Output:
// 1
// 2
}
func ExamplePrint() {
l := list.Cons(list.T1(1), list.Cons(list.T1(2), list.Cons(list.T1(3), nil)))
list.Print(l, os.Stdout)
// Output:
// (1 2 3)
}
func ExampleReverse() {
l := list.Cons(list.T1(1), list.Cons(list.T1(2), list.Cons(list.T1(3), nil)))
list.Print(list.Reverse(l), os.Stdout)
// Output:
// (3 2 1)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment