Skip to content

Commit

Permalink
Merge pull request #57 from skx/52-divide
Browse files Browse the repository at this point in the history
Ensure the single-argument version of (/ x) works.
  • Loading branch information
skx authored Oct 17, 2022
2 parents 1290c5b + 2a5ee41 commit 5a05e83
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
9 changes: 9 additions & 0 deletions builtins/builtins.go
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,14 @@ func divideFn(env *env.Environment, args []primitive.Primitive) primitive.Primit
return primitive.Error(fmt.Sprintf("argument '%s' was not a number", args[0].ToString()))
}

// If there is only one argument then we return the
// reciprocal.
//
// (i.e. "(/ 3)" == ".3333"
if len(args) == 1 {
return primitive.Number(1 / v)
}

// now process all the rest of the arguments
for _, i := range args[1:] {

Expand Down Expand Up @@ -642,6 +650,7 @@ func fileWriteFn(env *env.Environment, args []primitive.Primitive) primitive.Pri
}
return primitive.Nil{}
}

// gensymFn is the implementation of (gensym ..)
func gensymFn(env *env.Environment, args []primitive.Primitive) primitive.Primitive {
// symbol characters
Expand Down
40 changes: 39 additions & 1 deletion builtins/builtins_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,16 @@ func TestDirectoryEntries(t *testing.T) {
// TestDivide tests "*"
func TestDivide(t *testing.T) {

// Test for "equality"
//
// Because floating points are hard
almostEqual := func(a, b float64) bool {
// Arbitrary equality threshold
float64EqualityThreshold := float64(1.0 / 1000000)

return math.Abs(a-b) <= float64EqualityThreshold
}

// No arguments
out := divideFn(ENV, []primitive.Primitive{})

Expand Down Expand Up @@ -630,6 +640,35 @@ func TestDivide(t *testing.T) {
if n != 4 {
t.Fatalf("got wrong result")
}

// Test only a single argument.
out = divideFn(ENV, []primitive.Primitive{
primitive.Number(12),
})

// Will work
n, ok2 = out.(primitive.Number)
if !ok2 {
t.Fatalf("expected number, got %v", out)
}
if !almostEqual(float64(n), 0.083333) {
t.Fatalf("got wrong result: %f", n)
}

// Another test
out = divideFn(ENV, []primitive.Primitive{
primitive.Number(-3),
})

// Will work
n, ok2 = out.(primitive.Number)
if !ok2 {
t.Fatalf("expected number, got %v", out)
}
if !almostEqual(float64(n), -(1 / 3.0)) {
t.Fatalf("got wrong result: %f", n)
}

}

// TestEnsureHelpPresent ensures that all our built-in functions have
Expand Down Expand Up @@ -1288,7 +1327,6 @@ func TestFileWrite(t *testing.T) {
// remove the direcotry
os.RemoveAll(path)


failure := fileWriteFn(ENV, []primitive.Primitive{
primitive.String(target),
primitive.String("cake")})
Expand Down

0 comments on commit 5a05e83

Please sign in to comment.