M
Modular11mo ago
Dania

Why doesn't __bool__ allow explicit conversion?

I am playing with "Low level IR" level and it works great. However when i try to print out OurBool i get errors stating that OurBool can not be converted to Bool despite having a __bool__ method. I am using Mojo 6.1
@register_passable("trivial")
struct OurBool:
var value: __mlir_type.i1

fn __init__(value: __mlir_type.i1) -> Self:
return Self {value: value}

fn __bool__(self) -> Bool:
return Bool(self.value)


fn main():
let a = OurBool(__mlir_attr.`true`)
if a:
print('a is True')
# This works

print(a)
# This does not:
# /home/danil/source/mjtest/main.mojo:37:10: error: no matching function in call to 'print':
# print(a)
# ...
# /home/danil/source/mjtest/main.mojo:1:1: note: candidate not viable: argument #0 cannot be converted from 'OurBool' to 'Bool'
# alias OurTrue = OurBool(__mlir_attr.`true`)

print(Bool(a))
# The explicit conversion does not work too
@register_passable("trivial")
struct OurBool:
var value: __mlir_type.i1

fn __init__(value: __mlir_type.i1) -> Self:
return Self {value: value}

fn __bool__(self) -> Bool:
return Bool(self.value)


fn main():
let a = OurBool(__mlir_attr.`true`)
if a:
print('a is True')
# This works

print(a)
# This does not:
# /home/danil/source/mjtest/main.mojo:37:10: error: no matching function in call to 'print':
# print(a)
# ...
# /home/danil/source/mjtest/main.mojo:1:1: note: candidate not viable: argument #0 cannot be converted from 'OurBool' to 'Bool'
# alias OurTrue = OurBool(__mlir_attr.`true`)

print(Bool(a))
# The explicit conversion does not work too
4 Replies
Xcur
Xcur11mo ago
Try doing bool(a) instead with a lower case b. Bool should be a SIMD type im pretty sure
Dania
DaniaOP11mo ago
It throws "use of unknown declaration 'bool'" error. I guess there is no lowercase bool() in mojo yet
Xcur
Xcur11mo ago
Ahhh okay I think it’s because traits aren’t complete yet and they don’t have a boolable trait. They talked about doing implicit conformance for traits in the newest newsletter, so my guess is in the next major release bool(a) will work
Dania
DaniaOP11mo ago
Thanks! That's what it was. Works as expected(provided explicit declaration) with already implemented Stringable trait and corresponding __str__
Want results from more Discord servers?
Add your server