Scheme function to reverse a list

后端 未结 4 1342
甜味超标
甜味超标 2021-01-16 13:36

For my programming languages class I\'m supposed to write a function in Scheme to reverse a list without using the pre-made reverse function. So far what I got was

4条回答
  •  盖世英雄少女心
    2021-01-16 14:10

    The problem with your implementation is that cons isn't receiving a list as its second parameter, so the answer you're building isn't a proper list, remember: a proper list is constructed by consing an element with a list, and the last list is empty.

    One possible workaround for this is to use a helper function that builds the answer in an accumulator parameter, consing the elements in reverse - incidentally, this solution is tail recursive:

    (define (reverse lst)
      (reverse-helper lst '()))
    
    (define (reverse-helper lst acc)
      (if (null? lst)
          acc
          (reverse-helper (cdr lst) (cons (car lst) acc))))
    
    (reverse '(1 2 3 4 5))
    => '(5 4 3 2 1)
    

提交回复
热议问题