How to increase counter in a do-loop within Scheme

2019-08-26 07:33发布

I want do a simple counter increase by one within a do-loop in Scheme language, but I'm not that familiar with the language and have tried many scripts without success. The code is going to be implemented in Ansys Fluent to read multiple case files:

(define j 5)
(Do ((i 10 (+ i 1))) ((>= i 20))
(ti-menu-load-string (format #f "/file/read-case \"C:/DataProcessing/Case~a-time~a-sec/test/Case~a-time~a-sec.cas\"" i j i j))
(set! j (+ j 1))
)

How to pass the new j value to the do-loop so that I get the folder and file names to change as follows:

Case10-time5-sec
Case11-time6-sec
...

I know that the (set! j (+ j 1)) is not the correct way to do things, but to give you an idea of what I'm trying to do. I don't think it should be difficult to call the variable when it changed value?

1条回答
老娘就宠你
2楼-- · 2019-08-26 08:21

In the list with vars you just add a nother term:

(do ((i 10 (+ i 1))
     (j 5  (+ j 1)))
    ((>= i 20) 'my-return-value)
  (ti-menu-load-string 
   (format #f "/file/read-case \"C:/DataProcessing/Case~a-time~a-sec/test/Case~a-time~a-sec.cas\"" i j i j)))
; ==> my-return-value (and as side effect prints some strings)

Know that do is just syntax sugar for a recursive function. You could do this without it like this with a named let:

(let function-name ((i 10) (j 5))
  (if (>= i 20)
      'my-return-value
      (begin 
        (ti-menu-load-string 
         (format #f "/file/read-case \"C:/DataProcessing/Case~a-time~a-sec/test/Case~a-time~a-sec.cas\"" i j i j))
        (function-name (+ i 1) (+ j 1)))))

Actually then you could make it functional by dividing producing and printing:

(define (make-strings)
  (let function-name ((i 10) (j 5) (result '()))
    (if (>= i 20)
        (reverse result)
        (function-name 
         (+ i 1) 
         (+ j 1) 
         (cons (format #f "/file/read-case \"C:/DataProcessing/Case~a-time~a-sec/test/Case~a-time~a-sec.cas\"" i j i j)
               result)))))

(for-each ti-menu-load-string (make-strings))

Nice thing about this is that you can unit test make-strings, extend it to take input variables etc..

查看更多
登录 后发表回答