Skip to content
This repository was archived by the owner on Apr 3, 2025. It is now read-only.
This repository was archived by the owner on Apr 3, 2025. It is now read-only.

It's already possible to overload the arithmetic operators +-*/ #35

Open

Description

https://gist.github.com/pyrocto/5a068100abd5ff6dfbe69a73bbc510d7

Some examples.  Complex numbers:
> Complex()({r:2, i:0} / {r:1, i:1})
< {r:1, i:-1}

Automatic differentiation.  Define f(x) = x^3 - 5x:
> let f = x => Dual()(x * x * x - {x:5, dx:0} * x);
Now map it over some values:
> [-2,-1,0,1,2].map(a => ({x:a, dx:1})).map(f).map(a => a.dx);
< [ 7, -2, -5, -2, 7 ]
i.e. f'(x) = 3x^2 - 5

Polynomials:
> Poly()([1,-2,3,-4]*[5,-6]).map((c, p)=>''+c+'x^'+p).join(' + ')
< "5x^0 + -16x^1 + 27x^2 + -38x^3 + 24x^4"

Big rational numbers: 
> Rat()([112341324242, 22341234124] + [334123124, 5242342])
< [2013413645483934535, 29280097495019602]
Also supports the format n<digits>d<digits> for numerator and denominator:
> with(Rat){Rat()(n112341324242d22341234124 + n334123124d5242342).join(' / ')}
< "2013413645483934535 / 29280097495019602"

Strings:
> Str()((['Hi '] + ['there! ']) * [3]) 
< ["Hi there! Hi there! Hi there! "]
> with(Str){Str()((cow+boy)*[5])}
< ["cowboycowboycowboycowboycowboy"]
The + operator is necessarily commutative, though, so this isn't the best use case:
> with(Str){Str()(cow+boy*[5])}
< ["boyboyboyboyboycow"]

Activity

  1. fuunnx commented on Aug 27, 2020

    @fuunnx

    🤯

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions