Datatype comparisons, choosing opposite condition
Monkey Forums/Monkey Beginners/Datatype comparisons, choosing opposite condition
| ||
Strict
Class Entity
End
Class Person Extends Entity
End
Class Cat Extends Entity
End
Function Main:Int()
Local p:Person = new Person
Local c:Cat = new Cat
If Person(p)
Print("The p object is an instance of the Person class")
End
If Entity(p) And Entity(c)
Print("Both p and c objects are derived from the Entity base class")
End
Return 0
End
I am interested to know if it is possible to make negative type comparisons. For example if c variable is checked against the Person class Person(c) Instead of not letting the program compile, it would be better to just take it as a false and ignore the if statement. I don't know if this brings troubles and incompatibilities, anyway I just wanted to mention it here for the sake of it and we will see what happens. |
| ||
| Instead of not letting the program compile, it would be better to just take it as a false and ignore the if statement. Do you mean that you like to remove 'Person' some times? You could use the preprocessor for that. Or something like this? |
| ||
| Hi Pharmhaus, thanks for responding. I liked the second example you offered, that this is also correct approach. What I am bothered mostly is about having precise type to type comparison. I found that the code works only if the objects are derived from a base class, otherwise the comparison will never happen. What Monkey understands is that you try to convert a person to a cat in order to compare it's datatype. Which this is impossible and hence the program fails to compile.
Strict
Class Entity
End
Class Person Extends Entity
End
Class Cat Extends Entity
End
Function DoIt:Void(entity:Entity)
If Cat(entity)
Print("Meow!")
End
If Person(entity)
Print("Hello!")
End
End
Function Main:Int()
Local p:Person = new Person
Local c:Cat = new Cat
DoIt(p)
DoIt(c)
' This won't compile
'If Cat(p)
'' Print("")
'End
If Cat(Entity(p))
Print("Please replace logic processing unit")
Else
Print("Correct: Person object is not instance of Cat class")
End
Return 0
End
I don't know what is this about, as far I understand is a concept very familiar to C programmers. Personally I have used only PHP and C# so I am more convenient with reflection and dynamism. |
| ||
| Ahh, I see you try to do something similiar to duck typing. sorry, that is not possible in the way you would like to do it, you would like to use polymorphism instead. Anyway, I remeber that I wrote something like this some time ago, I will see if it is still around somewhere. Using simple polymorphism: Using reflection to get some type of ducktyping/type checking: (Please note: reflection increases compilation time and is not the fastest) |
| ||
| Wow this example took it to the next level. Monkey is indeed powerful language. Thanks for posting. |