开发者

Scheme: sequential execution

开发者 https://www.devze.com 2023-02-15 12:05 出处:网络
I need to do something basically like this: (define test (λ (ls1 ls2) (cond ((empty? ls2) null) (else (append ls1 (car ls2)) (test ls1 (cdr ls2))) (displayln ls1))))

I need to do something basically like this:

(define test
  (λ (ls1 ls2)
    (cond
      ((empty? ls2) null)
      (else
       (append ls1 (car ls2)) (test ls1 (cdr ls2))) (displayln ls1))))

The issue is the else-clause and the function that follows it. I need both clauses of the else-clause to execute and then I need the last function to execute but I can't get the syntax right.

I need (test '(1 2 3) '(4 5 6)) to result in displaying '(1 2 3 4 5 6) and it has to use the 开发者_如何学编程recursive call.

Any advice is appreciated.

Thanks.


There is several problem there. First you make an append on a list and an atom (not a list)... at least if (car l2) is not a list. Second you probably think that (append l1 (list (car l2)) modifies l1. But this is not the case. The result is a new list.

To sequence your operation you can do as larsmans have said. But you can also write the following

(define (test l1 l2)
  (if (null? l2)
      (displayln l1)
      (let ((l1-follow-by-car-l2 (append l1 (list (car l2)))))
        (test l1-follow-by-car-l2 (cdr l2)) ))  

This has exactly the same behavior.


If you desperately want to solve this recursively, and you don't care about the return value, use

(define (test l1 l2)
  (if (null? l2)
    (displayln l1)
    (test (append l1 (list (car l2))) (cdr l2))))

(This is very inefficient btw: O(n × m) memory allocations.)

0

精彩评论

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