89 lines
1.9 KiB
Go
89 lines
1.9 KiB
Go
|
package calc
|
||
|
|
||
|
import (
|
||
|
"gitea.zaclys.com/bvaudour/gob/number"
|
||
|
"gitea.zaclys.com/bvaudour/gob/option"
|
||
|
)
|
||
|
|
||
|
type integer interface {
|
||
|
~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
|
||
|
}
|
||
|
|
||
|
func Op1(cb number.Op1Func) CalcFunc {
|
||
|
return func(c *Calc) (err option.Option[error]) {
|
||
|
result := c.stack.Pop()
|
||
|
if n, ok := result.Ok(); ok {
|
||
|
c.Push(cb(n))
|
||
|
} else if e, ok := result.Err(); ok {
|
||
|
c.Reset()
|
||
|
err = option.Some(e)
|
||
|
}
|
||
|
|
||
|
return
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func Op2(cb number.Op2Func) CalcFunc {
|
||
|
return func(c *Calc) (err option.Option[error]) {
|
||
|
result := c.stack.Pop2()
|
||
|
if n, ok := result.Ok(); ok {
|
||
|
c.Push(cb(n.N1, n.N2))
|
||
|
} else if e, ok := result.Err(); ok {
|
||
|
c.Reset()
|
||
|
err = option.Some(e)
|
||
|
}
|
||
|
|
||
|
return
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func Reduce(cb number.ReduceFunc) CalcFunc {
|
||
|
return func(c *Calc) (err option.Option[error]) {
|
||
|
if c.stack.IsEmpty() {
|
||
|
err = option.Some(ErrIsEmpty(errStack))
|
||
|
} else {
|
||
|
n := cb(c.Stack()...)
|
||
|
c.Reset()
|
||
|
c.Push(n)
|
||
|
}
|
||
|
|
||
|
return
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func ConvertToBase[N integer](base N) number.Op1Func {
|
||
|
return func(n number.Number) number.Number {
|
||
|
return number.ToBase(n, base)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func ConvertToInteger[N integer](base ...N) number.Op1Func {
|
||
|
return func(n number.Number) number.Number {
|
||
|
return number.ToInteger(n, base...)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func ConvertToDecimal[N integer](base ...N) number.Op1Func {
|
||
|
return func(n number.Number) number.Number {
|
||
|
return number.ToDecimal(n, base...)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func ConvertToFraction[N integer](base ...N) number.Op1Func {
|
||
|
return func(n number.Number) number.Number {
|
||
|
return number.ToFraction(n, base...)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func ConvertToScientific[N integer](base ...N) number.Op1Func {
|
||
|
return func(n number.Number) number.Number {
|
||
|
return number.ToScientific(n, base...)
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func ConvertRound(precision uint64, base ...uint) number.Op1Func {
|
||
|
return func(n number.Number) number.Number {
|
||
|
return number.Round(n, precision, base...)
|
||
|
}
|
||
|
}
|