Skip to content

Instantly share code, notes, and snippets.

@kjessup
Created April 3, 2014 20:01
Show Gist options
  • Save kjessup/9961760 to your computer and use it in GitHub Desktop.
Save kjessup/9961760 to your computer and use it in GitHub Desktop.
This object attempts to work like a decimal, but is able to store its formatting flags, much in the manner of LP8.
define formatted_decimal => type {
    data public value::decimal,
        private flags
     
    public onCreate(flags = (:)) => {
        .value = 0.0
        .flags = #flags
    }
    public onCreate(v::decimal, flags = (:)) => {
        .value = #v
        .flags = #flags
    }
    public onCreate(v, flags = (:)) => {
        .value = decimal(#v)
        .flags = #flags
    }
 
    public setFormat(...rest) => {
        .flags = #rest
    }
     
    public asString() => .value->asString(:.flags or (:))
     
    public +(rhs::formatted_decimal)::formatted_decimal => formatted_decimal(.value + #rhs->value, .flags)
    public +(rhs::decimal)::formatted_decimal => formatted_decimal(.value + #rhs, .flags)
    public +(rhs::integer)::formatted_decimal => formatted_decimal(.value + #rhs, .flags)
     
    public -(rhs::formatted_decimal)::formatted_decimal => formatted_decimal(.value - #rhs->value, .flags)
    public -(rhs::decimal)::formatted_decimal => formatted_decimal(.value - #rhs, .flags)
    public -(rhs::integer)::formatted_decimal => formatted_decimal(.value - #rhs, .flags)
     
    public /(rhs::formatted_decimal)::formatted_decimal => formatted_decimal(.value / #rhs->value, .flags)
    public /(rhs::decimal)::formatted_decimal => formatted_decimal(.value / #rhs, .flags)
    public /(rhs::integer)::formatted_decimal => formatted_decimal(.value / #rhs, .flags)
     
    public *(rhs::formatted_decimal)::formatted_decimal => formatted_decimal(.value * #rhs->value, .flags)
    public *(rhs::decimal)::formatted_decimal => formatted_decimal(.value * #rhs, .flags)
    public *(rhs::integer)::formatted_decimal => formatted_decimal(.value * #rhs, .flags)
     
    public onCompare(rhs)::integer => .value->onCompare(#rhs)
}
 
define decimal->/(rhs::formatted_decimal) => formatted_decimal(self / #rhs->value)
define integer->*(rhs::formatted_decimal) => self * #rhs->value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment