Skip to content

Instantly share code, notes, and snippets.

@paulohrpinheiro
Created May 25, 2020 10:44
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 paulohrpinheiro/95c76717b9078bf081038d11b1654926 to your computer and use it in GitHub Desktop.
Save paulohrpinheiro/95c76717b9078bf081038d11b1654926 to your computer and use it in GitHub Desktop.
Scheme primitives
package primitives
import (
"errors"
"reflect"
)
// The definitions in functions are from THE book:
// Friedman & Felleisen. The Little Schemer, Fourth Edition, MIT Press, 1996.
// The Law of Car:
// The primitive *car* is defined only for non-empty lists.
// (p. 5)
func car(v interface{}) (interface{}, error) {
wrapper := reflect.ValueOf(v)
// v is not a list
if !(wrapper.Kind() == reflect.Array || wrapper.Kind() == reflect.Slice) {
return nil, errors.New("Not a list")
}
// wrapper is an empty list
if wrapper.Len() == 0 {
return nil, errors.New("Empty list")
}
// Returns the first element of the list, indicating no error
return wrapper.Index(0), nil
}
package primitives
import "testing"
func TestCar(t *testing.T) {
var tests = []struct {
input []int
want int
}{
{[]int{10, 20}, 10},
{[]int{30}, 30},
}
for _, test := range tests {
if got, _ := car(test.input); got != test.want {
t.Errorf("car(%v)=%v, got %v", test.input, test.want, got)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment