Jonathan
Jonathan

Reputation: 608

Scheme How To Test 2 Conditions in one Clause?

I need to create a sub-function that will return me all the adjacent node, which I needed for this question in Scheme. I'm new to scheme, not sure how I can combine two conditions into one test case ?

Basically my algorithm is to test if the node is on the edge or not. This case I use a 5x5 grid.

If both node is on the corner meaning both is equal to either 1 or 5, than I will have only 2 adjacent node. If only one of the node is hit the edge, I will have 3 node return value. If no edge around the node, I will have 4 node return.

My problem is how can I put 2 test case in one clause ?

(define (neighbors l w)
  (if (= 1 l) and (= 1 w)
      (display l w))) --at top left corner

Here I want to evaluate if l and w are both equal to 1. Now this doesn't work because I can't use "and" "or" such keywords in the syntax nor I can use & or + to combine them. Any ideas ? Or I should do something else ?

Upvotes: 3

Views: 5526

Answers (2)

Vijay Mathew
Vijay Mathew

Reputation: 27174

when and unless are more convenient than if, when there is only one branch to the conditional:

(define (neighbors l w)
  (when (and (= 1 l) (= 1 w))
     (display l) 
     (display #\space) 
     (display w) 
     (newline)))

Note that when’s branch is an implicit begin, whereas if requires an explicit begin if either of its branches has more than one form.

Not all Schemes has when and unless predefined as they are not specified in R5RS. It's easy to define them as macros:

(define-syntax when
   (syntax-rules ()
     ((_ test expr1 expr2 ...)
      (if test
      (begin
        expr1
        expr2 ...)))))

(define-syntax unless
  (syntax-rules ()
    ((_ test expr1 expr2 ...)
     (if (not test)
     (begin
       expr1
       expr2 ...)))))

Upvotes: 3

Nettogrof
Nettogrof

Reputation: 2136

Have you tried this:

(define (neighbors l w)
  (if (and (= 1 l) (= 1 w))
     (display l w))) --at top left corner

Because when I look to this , it seems to work that way

Upvotes: 8

Related Questions