Created
May 25, 2020 10:44
-
-
Save paulohrpinheiro/95c76717b9078bf081038d11b1654926 to your computer and use it in GitHub Desktop.
Scheme primitives
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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