On Sat, 21 Jun 2014, Patrik Karlsson wrote:
> Many years ago when I was programming in Delphi I used to have object
> arrays of size 2 and referencing to the element index with true and false.
> This was very very useful.
> 
> It was possible since false=0 and true=+1.
> In Gambas we have false=0 and true=-1.
> 
> So now I came up with:
>   Dim sMoods As String[] = ["Sad", "Happy"]
>   Dim bHappiness As Boolean
> 
>   Debug CInt(True), Abs(True), Abs(CInt(True))
>   Debug CInt(False), Abs(False), Abs(CInt(False))
> 
>   bHappiness = False
>   Debug "bHappiness= "; bHappiness; ": " & sMoods[Abs(CInt(bHappiness))]
>   Debug "bHappiness= "; bHappiness; ": " & sMoods[If(bHappiness, 1, 0)]
> 
>   bHappiness = True
>   Debug "bHappiness= "; bHappiness; ": " & sMoods[Abs(CInt(bHappiness))]
>   Debug "bHappiness= "; bHappiness; ": " & sMoods[If(bHappiness, 1, 0)]
> 
> 1. Why is Abs(True) True?
> 

Because the mapping Integer -> Boolean is not injective. The rule is: 0 maps
to False, everything else maps to True. To be able to map Boolean -> Integer
the convention used in Gambas is False maps to zero (of course) and True maps
to -1, which makes actually sense if you don't look into the array index but
into the bit flags direction (True means "all bits set" in Gambas, which is
what -1 is in two's complement). So what happens is:

Abs(True) becomes Abs(CInt(True)) on the fly which is Abs(-1) = 1 which is
non-zero and thus True again.

> 2. Which is fastest, Abs(CInt(... or If(... ? I guess that If(... is more
> future proof.
> 

IIf() (or If() for short) is likely to be more expensive because it needs to
evaluate both expressions, the true and the false one, before it decides
which to use. Since these are only numbers in your use case, it's really
hard to say - and I bet even harder to measure anyways.

> 3. I have a "BoolToIndex" function in a library module but I was thinking
> if it should not be part of the language, to be able to reference in
> a _simple_ way to an array element with a boolean.
> 

I don't know.

If I have to do what you want, I skip the array indirection and simply do:

  Debug IIf(bHappiness, ("Happy"), ("Sad"))

Since you want only Boolean indices, it's never going to be more code to
type...

Regards,
Tobi

-- 
"There's an old saying: Don't change anything... ever!" -- Mr. Monk

------------------------------------------------------------------------------
HPCC Systems Open Source Big Data Platform from LexisNexis Risk Solutions
Find What Matters Most in Your Big Data with HPCC Systems
Open Source. Fast. Scalable. Simple. Ideal for Dirty Data.
Leverages Graph Analysis for Fast Processing & Easy Data Exploration
http://p.sf.net/sfu/hpccsystems
_______________________________________________
Gambas-user mailing list
Gambas-user@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/gambas-user

Reply via email to