Re: Cannot convert type bool to type int?

1,536 views
Skip to first unread message

Steven Degutis

unread,
Aug 1, 2012, 7:13:47 PM8/1/12
to golan...@googlegroups.com
In that case it makes more sense to add it as a function in the math package with the same name you gave it.

-Steven


On Wednesday, August 1, 2012 6:00:43 PM UTC-5, Uli Kunitz wrote:
I would like to write int(x > y). The go compiler states that it cannot convert x > y (type bool) to type int. Sure the language specification doesn't support it, but I wonder why this is the case. I understand that Go doesn't support implicit type conversions and I'm fine with that.

The explicit conversion would be well defined: false will be 0 and true will be 1. There is even a mathematical notation for it: [x > y]. Graham, Knuth and Patashnik call it Iverson convention in "Concrete Mathematics" stating that Kenneth A. Iverson introduced it in his programming language APL. Sure you can implement your own Iverson function, but 6g doesn't do any optimization on it, so there is a real price to pay here. C doesn't have the issue because all operators returning Boolean values have type int by definition and implicit conversion of the _Bool type is supported.

Currently I'm using my own Iverson() function, because I have functions returning bool that need to be used as int in a specific context. From my viewpoint that is the typical use case for an explicit conversion.







Thomas Bushnell, BSG

unread,
Aug 1, 2012, 8:26:46 PM8/1/12
to Uli Kunitz, golan...@googlegroups.com

Can you give an example of its use in a case where boolean operators are not sufficient?

Nigel Tao

unread,
Aug 1, 2012, 9:08:56 PM8/1/12
to Thomas Bushnell, BSG, Uli Kunitz, golan...@googlegroups.com
On 2 August 2012 10:26, Thomas Bushnell, BSG <tbus...@google.com> wrote:
> Can you give an example of its use in a case where boolean operators are not
> sufficient?

I've needed it in the VP8 decoder. See the btou definition and its callers in
http://code.google.com/p/vp8-go/source/browse/vp8/reconstruct.go#145

As for the OP, I would (and have) just write the trivial function, and
place it in your package. 6g will at least inline the function, and if
profiling indicates that it is a significant bottleneck (which I
doubt), we can make the compilers do more. Also, you could try gccgo.

Uli Kunitz

unread,
Aug 2, 2012, 2:56:15 AM8/2/12
to golan...@googlegroups.com, Thomas Bushnell, BSG, Uli Kunitz
Nigel, many thanks. Your version of the function is indeed inlined and I will use it going forward.
Reply all
Reply to author
Forward
0 new messages