Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Title says it all. Given some input, turn it into a boolean value (0 or 1), without using conditional statements (e.x. == > < <= >= != ~=), or any function which uses conditional statements within its implementation, such as if, while and for. Your program must work with floating points, although you get more if it works with other items.

A general rule for determining whether bool(item) is False is if the item is empty ('' is an empty string, [] is an empty list.), or if the function used to turn an item of one type into another is given no input (in Python, str() returns '', list() returns [].)

Here are (some of) the different valid types. Your program is considered to work with one type if it works with one item in the following lists:

  • Integers, floating points, doubles, longs
  • Strings
  • Lists, tuples, arrays (bytearrays)
  • Dictionaries
  • Functions
  • Objects/Classes

Program score will be calculated like this: [# of characters]-(50*[# of types]). The program with the smallest score wins the challenge.

share|improve this question

closed as unclear what you're asking by Jan Dvorak, Quincunx, ProgramFOX, Timtech, Doorknob Mar 5 at 14:09

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question.If this question can be reworded to fit the rules in the help center, please edit the question.

    
This problem is deceptively difficult. Perhaps a more concise wording would be to disallow any language construct which passively performs a boolean conversion (as &&, ||, while, for(;foo;), etc. all do). –  primo Dec 24 '12 at 19:25
    
Would you give an example of valid input that does not use comparison operators (such as == > < <- >= !=)? I must be missing something. It seems to me that they are essential elements of the sorts of propositions one wishes to assess. –  David Carraher Dec 24 '12 at 20:00
    
How do you measure how many types you handle? Do types such as float/double count as a single floating-point type or two separate types? –  MrZander Dec 24 '12 at 20:33
1  
How can this possibly be language-agnostic? The problem definition makes various assumptions that seem to tie it to Python and close relatives, and the scoring system lets some languages claim a score of -Infinity. –  Peter Taylor Dec 25 '12 at 11:55
1  
@PeterTaylor as I understand it, there are only 7 different 'types' possible, ergo a maximum (or rather, minimum) of -350 bonus. Although, I do agree that Set/Frozenset only applies to very few languages, and probably shouldn't be included. –  primo Dec 25 '12 at 12:20

8 Answers 8

Python - 122 chars - 50*13 types = -528

def b(x=False):
 try:return[False][x]
 except IndexError:return True
 except:
  try:return b(len(x))
  except:return True

Works for the following built-in types (as listed in §3.2 The standard type hierarchy)

  1. NotImplemented
  2. Ellipsis
  3. int
  4. long
  5. bool
  6. string
  7. unicode
  8. tuple
  9. list
  10. bytearray
  11. set
  12. frozenset
  13. dict
share|improve this answer
    
Using exceptions to emulate conditionals... seems to simple, in retrospect ;) –  primo Dec 25 '12 at 4:24
    
What you have there seems to be 121 characters, not 122 :) Also, you can save one more character by passing instead of returning True and then doing that at the end. –  minitech Dec 31 '12 at 0:33

MMIX (8 bytes assembled)

Assembly language has no statements.

bool    ZSNZ $0,$0,1
        POP  1,0
share|improve this answer

JavaScript, -278

function bool(_,$){try{$=_.length;$._;_=$}catch(_){}return 1-isNaN(_/_)}

Doesn’t use any boolean operators! If global leaking and input is okay, then it’s even shorter, at 65 characters:

bool=eval.bind(0,'try{$=_.length;$._;_=$}catch(_){}1-isNaN(_/_)')

Works for anything with a length and all primitive types and their object wrappers.

Now you've added a list of things that count as types, but what kind of function or class should evaluate to false? This one treats functions that take no arguments as false - does that count? What about classes? What does that mean?

share|improve this answer
    
You have numbers, strings, arrays and dictionaries, functions, and object; giving you the best bonus: -350. So, your score is -278. –  FakeRainBrigand Jan 6 '13 at 19:26
    
@FakeRainBrigand: Ah, the question was updated. Thanks. But it doesn't work with functions. (Well, it does, but what's an "empty" function anyways? This one will detect a function that takes no arguments.) –  minitech Jan 6 '13 at 19:36

Scala(152 characters)

implicit def?(a:Any)={val f=false;a match{case 0=>f;case null=>f;case ""=>f;case ()=>f;case None=>f;case x:Iterable[_]=>x.exists(_=>true)case _=>true}}

Sample inputs:

scala> if(0) true else false
res0: Boolean = false

scala> if(0.0) true else false
res1: Boolean = false

scala> if(1) true else false
res2: Boolean = true

scala> if(()) true else false
res3: Boolean = false

scala> if(List()) true else false
res4: Boolean = false

scala> if(List(1)) true else false
res5: Boolean = true

scala> if(Set()) true else false
res6: Boolean = false

scala> if("") true else false
res7: Boolean = false

scala> if(Map()) true else false
res8: Boolean = false

scala> if(None) true else false
res9: Boolean = false

scala> class X
defined class X

scala> if(new X()) true else false
res10: Boolean = true
share|improve this answer

GoRuby, 19 - 50*(number of types in Ruby)

def bool(o)
   [1,[o].fle.j.sz].mi
end

Returns 0 if the passed object converts to the empty string, 1 otherwise. Of course, Ruby doesn't treat 0 as false, so this isn't a very useful function...in fact, bool(bool(x)) is always 1. Objects that do convert to 0 include nil,false,[], and lists containing only objects that convert to 0.

share|improve this answer

Python 85 chars - 50*20 types = -915 points

def b(x=False):
 try:return b(len(x))
 except:return{0:False,None:False}.get(x,True)

So it works for all types in the six categories in the question. The score is therefore 85 - 50*6 = -215, or am I wrong?

Here is also my test code:

class Test(object):
  def __init__(self):
    pass

for x in [None, NotImplemented, Ellipsis, 
    0,1,0L,1L,False,True,0.0,1.0,0.0j,1.0j,
    '','a',u'',u'a',
    (),(1,),[],[1],bytearray(),bytearray('31'),
    set(),set('ab'),frozenset(),frozenset('ab'),
    {},{'a':0},b, Test, Test.__init__,(a for a in 'a')]:
  print b(x), bool(x), type(x)

Think I've forgotten some types ;-)

b(x) bool(x) type(x)
False False <type 'NoneType'>
True True <type 'NotImplementedType'>
True True <type 'ellipsis'>
False False <type 'int'>
True True <type 'int'>
False False <type 'long'>
True True <type 'long'>
False False <type 'bool'>
True True <type 'bool'>
False False <type 'float'>
True True <type 'float'>
False False <type 'complex'>
True True <type 'complex'>
False False <type 'str'>
True True <type 'str'>
False False <type 'unicode'>
True True <type 'unicode'>
False False <type 'tuple'>
True True <type 'tuple'>
False False <type 'list'>
True True <type 'list'>
False False <type 'bytearray'>
True True <type 'bytearray'>
False False <type 'set'>
True True <type 'set'>
False False <type 'frozenset'>
True True <type 'frozenset'>
False False <type 'dict'>
True True <type 'dict'>
True True <type 'function'>
True True <type 'type'>
True True <type 'instancemethod'>
True True <type 'generator'>
share|improve this answer

Bash

Bash only does integer arithmetic of numbers stored in strings. So this isn't really a proper answer as there are no floats. But I thought this was an interesting integer-only solution:

$ bool () { echo $(( (($1 * $1) + 2) % (($1 * $1) + 1) )); }
$ for i in {-5..5}; do bool $i; done
1
1
1
1
1
0
1
1
1
1
1
$ 
share|improve this answer

Perl, 5 char

1-!$x

Works for integers, floating-point values, strings, and C. Although in Perl, these are all the same type.

share|improve this answer
2  
! is a boolean operation –  FUZxxl Dec 25 '12 at 17:47

Not the answer you're looking for? Browse other questions tagged or ask your own question.