kazi siam
kazi siam

Reputation: 109

Multiple conditions without using boolean operators in Scheme

I don't know how to ask this question. Basically, my professor solved a problem where he didn't use boolean expression (and, or, not) in the cond statement. So, I tried to come up with a dummy example and I noticed something peculiar. As you can see below. I don't know why true false gives me false instead of going go to the else statement, but when I do false true, it goes to the else statement. I am treating this as an AND operator and I know I am wrong.

(cond ((= 2 2) (= 3 3))
      (else "Hello"))   ; --> T T --> #t

(cond ((= 2 2) (= 3 1))
      (else "Hello"))   ; --> T F --> #f

(cond ((= 2 1) (= 3 3))
      (else "Hello"))   ; --> F T --> "Hello"

(cond ((= 2 1) (= 3 1))
      (else "Hello"))   ; --> F F --> "Hello"

Upvotes: 1

Views: 214

Answers (2)

molbdnilo
molbdnilo

Reputation: 66431

The cond syntax is

(cond (condition1 value1)
      (condition2 value2)
      ...
      (conditionN valueN))

So your conditions are (= 2 2), (= 2 1), and else (which is equivalent to #t in a cond-expression), and the possible values are (= 3 3), (= 3 1), and `"Hello".

And

(cond (condition value1) 
      (else value2))

is equivalent to

(if condition value1 value2)

so you have the equivalent of

(if (= 2 2)
    (= 3 3)
    "Hello")

(if (= 2 2)
    (= 3 1)
    "Hello")

and so on.

Upvotes: 1

Sorawee Porncharoenwase
Sorawee Porncharoenwase

Reputation: 6502

There are three equations that you should know.

1.

(cond
  [#t <A>]
  .........)

evaluates to <A>.

2.

(cond
  [#f <A>]
  .........)

evaluates to

(cond
  .........)

That is, when the LHS of a clause is #f, just "cross out" that clause.

3.

(cond
  [else <A>])

evaluates to <A>.

In your examples:

1.

(cond ((= 2 2) (= 3 3))
      (else "Hello"))

=

(cond (#t (= 3 3))
      (else "Hello"))

By using the first equation, we get that the result should be (= 3 3) = #t.

2.

(cond ((= 2 2) (= 3 1))
      (else "Hello"))

=

(cond (#t (= 3 1))
      (else "Hello"))

By using the first equation, we get that the result should be (= 3 1) = #f.

3.

(cond ((= 2 1) (= 3 3))
      (else "Hello"))

=

(cond (#f (= 3 3))
      (else "Hello"))

By using the second equation, we get that it should evaluate to:

(cond (else "Hello"))

By using the third equation, we get that it should evaluate to "Hello".

4.

(cond ((= 2 1) (= 3 1))
      (else "Hello"))

=

(cond (#f (= 3 1))
      (else "Hello"))

By using the second equation, we get that it should evaluate to:

(cond (else "Hello"))

By using the third equation, we get that it should evaluate to "Hello".

Upvotes: 4

Related Questions