#2 - Binary operators

Thanks to everybody helping me to discuss Pif.

We have seen some really nice polymorphic functions as EWD/...,
Pif, State Machine.

The discussion I started was meant to underline the Rebol
capability of having functions taking unlimited number of
arguments through the use of a one block argument, whose contents
are interpreted somehow.

But, I think, that the functions with a limited number of
arguments may be even more polymorphic and more interesting.

Let's try a "real world" (just kidding 8^) example:

the task is to solve the equation:

    x + a = b

, where A and B are given and X is unknown:

solve: func [
    {Solve the equation x + a = b}
    a b
] [
    b - a
]

The question is: Is this solution polymorphic?

Answer #1: Yes, you can solve the cases like:

solve 1 10
solve exp 1 pi
solve #"x" #"y"
solve 16:26 19:00
solve $1 $1'000'000
solve 25/1/2000 31/1/2000

OTOH, the answer may be:

Answer #2: No, if we consider the following case:

complex!: make object! [
    re: 0
    im: 0
]

solve make complex! [re: 0 im: 0] make complex! [re: 1 im: 2]

, because I didn't find other way to accomplish this than to
rewrite Solve.

If we used a slightly different version of Solve from the start
like this:

solve: func [
    {Solve the equation x + a = b}
    a b
] [
    subtract b a
]

, then it would have been much more polymorphic.
Now the only thing that is needed is to define the following:

complex?: func [x [any-type!]] [
    all [
        object? x
        in x 're
        in x 'im
        number? x/re
        number? x/im
    ]
]

_subtract: :subtract

subtract: func [
    {Returns the second value subtracted from the first.}
    value1 [any-type!]
    value2 [any-type!]
] [
    either all [complex? value1 complex? value2] [
        make complex! [
            re: value1/re - value2/re
            im: value1/im - value2/im
        ]
    ] [
        _subtract value1 value2
    ]
]

I do like this kind of polymorphism. It can be observed only when
using the prefix binary operators.

OTOH, I think, that there is an even better way, how to arrange
the things.

CU later,
    Ladislav

Reply via email to