Why is "0" considered a true value in the if statement in the Scheme?

I understand that zero is False. Then why is this treated as a true value in the following code, that is, why is it "returned"?

scm> (if 0 'a 'b)
'a

      

+3


source to share


3 answers


In the scheme only false value - #f

(though sometimes the alias false

is also determined with the same value), everything else is considered true - including: 0

, ""

, '()

, etc. So clear in this expression:

(if 0 'a 'b)

      



The value 0

is truthful, so the result is the entire expression evaluates to 'a

.

+5


source


Different languages make different decisions about whether nebulevye treated as Boolean values, and which - True

vs False

. For a comparison of behavior in some languages ​​see here .

A schema is a language that makes decisions:



  • you can use non-boolean values ​​in contexts that require booleans
  • any value other than the canonical false symbol #f

    is true.
0


source


Most LISPers have the same feeling about an empty list. Since the start for LISP nil

/ was ()

also the only false value. The schema entered #f

as false and kept it ()

as false for several reports until they were removed ()

as false. Thus, it #f

is only considered false.

You cannot change the report easily, so I suggest you do a procedure to do what you want:

(define (boolean x)
  (not (or (eq? x '())
           (eq? x #f)
           (eqv? x "")
           (eqv? x 0))))

(boolean "")           ; ==> #f
(if (boolean 0) 'a 'b) ; ==> b

      

Alternatively, if you use this a lot, you can make yourself a macro:

(define-syntax mif
  (syntax-rules ()
    ((_ predicate consequent alternative)
     (if (boolean predicate) consequent alternative))))

(mif 0 'a 'b) ; ==> b

      

With R6RS and R7RS, you can do this in the library and rename it as if

with (except (rnrs) if)

, and then you can import that instead (rnrs)

and get this behavior if

instead of the default. Note that you cannot change what is if

used with rnrs or other libraries, so you need to make your own versions of all the special forms that behave differently than you want. People reading your code can get confused.

0


source







All Articles