aboutsummaryrefslogtreecommitdiffstats
path: root/func.go
diff options
context:
space:
mode:
authorSam Anthony <sam@samanthony.xyz>2023-10-01 20:02:22 -0400
committerSam Anthony <sam@samanthony.xyz>2023-10-01 20:02:22 -0400
commit4f9e220638ea62443db25d252c4e12ede2c7f9c5 (patch)
treeed40edf989f2907e58e3d5fd0fd0a85cde919386 /func.go
parent6e3073f5e835b19b39d0853dece386067218b1ce (diff)
downloadpfc-4f9e220638ea62443db25d252c4e12ede2c7f9c5.zip
error handling and tidying
Diffstat (limited to 'func.go')
-rw-r--r--func.go43
1 files changed, 28 insertions, 15 deletions
diff --git a/func.go b/func.go
index 42763c0..c64e97a 100644
--- a/func.go
+++ b/func.go
@@ -73,32 +73,29 @@ func invTrig(fn string) func(Calculator) {
// Convert radians to degrees.
func deg(c Calculator) {
- if len(c.stack) > 0 {
- c.stack[len(c.stack)-1] = degrees(c.stack[len(c.stack)-1])
+ if n, err := c.stack.pop(); err == nil {
+ c.stack.push(degrees(n))
}
}
// Convert degrees to radians.
func rad(c Calculator) {
- if len(c.stack) > 0 {
- c.stack[len(c.stack)-1] = radians(c.stack[len(c.stack)-1])
+ if n, err := c.stack.pop(); err == nil {
+ c.stack.push(radians(n))
}
}
// Factorial (!).
func fac(c Calculator) {
- if len(c.stack) > 0 {
- a := &c.stack[len(c.stack)-1] // will replace with a!
- if float64(int(*a)) != *a { // undefined on non-ints
- return
- } else if int(*a) == 0 { // 0! = 1
- *a = 1.0
- } else { // a! = a*(a-1)!
- for i := int(*a) - 1; i > 1; i-- {
- *a *= float64(i)
- }
- }
+ n, err := c.stack.pop()
+ if err != nil {
+ return
+ }
+ if !isUint(n) { // undefined on non-ints
+ c.stack.push(n)
+ return
}
+ c.stack.push(float64(factorial(uint(n))))
}
// radians converts degrees to radians.
@@ -110,3 +107,19 @@ func radians(deg float64) float64 {
func degrees(rad float64) float64 {
return rad * 180 / math.Pi
}
+
+// factorial returns n! (n factorial).
+func factorial(n uint) uint {
+ if n == 0 { // 0! = 1
+ return 1
+ }
+ // n! = n*(n-1)!
+ for i := n - 1; i > 1; i-- {
+ n *= i
+ }
+ return n
+}
+
+func isUint(n float64) bool {
+ return float64(uint(n)) == n
+}