Skip to content

Standard library: comparing complex types for equality #245

@schoen

Description

@schoen

Project

library

Describe the feature

Describe the feature

I had to write a reasonably intricate function to compare Amount1 values for equality (because they're Either with unlike branches inside), and similarly for Asset1 values. It could be good to have these equality-testing functions available as standard library functions.

fn amount_equal(a_amt: Amount1, b_amt: Amount1) -> bool {
    match a_amt {
        Left(a: (u1, u256)) => {
            let (a1, a2): (u1, u256) = a;
            match b_amt {
                Left(b: (u1, u256)) => {
                    let (b1, b2): (u1, u256) = b;
                    and(jet::eq_1(a1, b1), jet::eq_256(a2, b2))
                },
                Right(b: u64) => false,
            }
        },
        Right(a3: u64) => match b_amt {
            Left(b: (u1, u256)) => false,
            Right(b3: u64) => jet::eq_64(a3, b3),
        },
    }
}

fn asset_equal(a_asset: Asset1, b_asset: Asset1) -> bool {
    match a_asset {
        Left(a: (u1, u256)) => {
            let (a1, a2): (u1, u256) = a;
            match b_asset {
                Left(b: (u1, u256)) => {
                    let (b1, b2): (u1, u256) = b;
                    and(jet::eq_1(a1, b1), jet::eq_256(a2, b2))
                },
                Right(b: u256) => false,
            }
        },
        Right(a3: u256) => match b_asset {
            Left(b: (u1, u256)) => false,
            Right(b3: u256) => jet::eq_256(a3, b3),
        },
    }
}

Alternatively, the infix == operator could have logic (assuming it doesn't already) to recursively destructure the types on the two sides of the equality and recursively confirm that the same branch of Left/Right or Some/None was taken, and that all contained and wrapped values are themselves equal. This would be a huge nuisance in a dynamically-typed language but is probably relatively feasible in a statically-typed language because there are probably a set of "destructure and recursively compare constituents for equality" rules that can be applied depending on the outer type. Cc @stringhandler

That solution actually seems best to me because there are unnamed complex types returned by jets, which people may conceivably want to compare for equality in some cases.

Metadata

Metadata

Assignees

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