Simplest Sign type

What would be the simplest/best way to encode sign, as in +1 or -1, as a type?

Here’s what I can think of:

  1. A type with an Int field which I then set to either +1 or -1 when setting an instance of said type, and then multiply the value of that field with whatever I want to change the sign of.
  2. A type with a Function field which is a function that multiplies its argument with either +1 or -1.
  3. Or somehow with “Value types”?

Am I over-thinking this…?

1 Like

You could use a Bool.

4 Likes

Or an enum.

It may depend on what other fields you have, how important it is to keep space to a minimum.
For example, the BigInt type encodes the sign of the number in the Int32 field that holds the size (i.e. if the size if negative, the number is negative)

All great ideas! OK, so there’s no one ultimate way.

Trying to understand the differences between value types and Enum…

What do you mean by value types?

this:
https://docs.julialang.org/en/stable/manual/types/#value-types

I’ll just add that in the vast and rich ecosystem of types that Julia has, it seems like maybe there should be some native Sign type…? This really seems like a fringe case that might not be worth it.
It would be similar to Bool, but function differently…
Just a thought.

What do you need to use the sign for?

In my specific case, I need to flip a normal vector to point to the opposite direction depending on a bunch of things.

Using a Bool like @dpsanders suggests looks like the best solution, and in many respects a Bool already acts like a “sign” type. Specifically:

  1. (-1)^boolvar is -1 / 1 according to boolean and has a specialized ^ method to make it fast.
  2. ifelse(boolvar,expr,-expr) could be used for negating.

It’s true sometimes a specialized type would help, but it can also burden (requiring specialized methods). The -1/1 <==> true/false <==> 0/1 correspondence is too strong to separate these values into different types.

I would consider having a Unit{T} type (or struct) which would represent the units of type T i.e. Sign for Reals, and unit circle for complex and 1/i/-1/-i for integer complex (Gaussian numbers). This type would satisfy abs(v) = v/unit(v) and other such relations which come in useful sometime.

3 Likes

Wah! Cool stuff, didn’t know the specialized ^ nor the ifelse function…

Thanks!

With the amount of new things being added, in base, and in packages, there’s always something new to learn in Julia! (I knew about ifelse, but also didn’t know that ^ had been specialized for ^boolval)
ifelse works very well by not causing a branch.

1 Like