views:

76

answers:

2

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 ?

+5  A: 

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

Nettogrof
right !! thanks! works and I should use the same for display as well
Jonathan
+3  A: 

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 ...)))))
Vijay Mathew
mm it seems to me that the "when" is an underfined reference identifier. It's not a native buildin scheme function in my library :(
Jonathan
@FS It is trivial to add "when" and "unless", if your Scheme do not have them. Please see the modified answer.
Vijay Mathew