开发者

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 "an开发者_运维百科d" "or" such keywords in the syntax nor I can use & or + to combine them. Any ideas ? Or I should do something else ?


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


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 ...)))))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜