首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带一个参数的方案函数,它将每两个元素交换一次

带一个参数的方案函数,它将每两个元素交换一次
EN

Stack Overflow用户
提问于 2015-05-13 06:58:52
回答 2查看 1.1K关注 0票数 1
代码语言:javascript
复制
(define (interchange list) 
    (if (empty? list)
        list
        (interchange (append (car (cdr list) X)))))

我需要创建一个函数来交换方案列表中的元素对。这就是我到目前为止想出的方法,但我在empty?中遇到错误

代码语言:javascript
复制
Error
empty?: undefined;
 cannot reference undefined identifier

function call                                       output
(interchange '( ))                                  ()
(interchange '(a))                                  (a)
(interchange '(a  b))                               (b a)
(interchange '(a  b  c))                            (b a c)
(interchange '(a  1  b  2  c  3  d  4))             (1 a 2 b 3 c 4 d)
(interchange '(hello  you  -12.34  5  -6  enough))  (you hello 5 -12.34 enough -6)
EN

回答 2

Stack Overflow用户

发布于 2015-05-13 07:31:17

试试这个:

代码语言:javascript
复制
(define (interchange lst)
  (if (or (null? lst) (null? (cdr lst)))       ; if the list has 0 or 1 elements left
      lst                                      ; then return the list, we're done
      (cons (cadr lst)                         ; otherwise grab the second element
            (cons (car lst)                    ; and the first element
                  (interchange (cddr lst)))))) ; and move forward two elements

诀窍是在每次迭代中处理两个元素,小心处理边缘情况。对于示例输入,它的工作方式与预期相同:

代码语言:javascript
复制
(interchange '())
=> '()
(interchange '(a))
=> '(a)
(interchange '(a  b))
=> '(b a)
(interchange '(a  b  c))
=> '(b a c)
(interchange '(a  1  b  2  c  3  d  4))
=> '(1 a 2 b 3 c 4 d)
(interchange '(hello  you  -12.34  5  -6  enough))
=> '(you hello 5 -12.34 enough -6)
票数 3
EN

Stack Overflow用户

发布于 2015-05-14 04:42:12

代码语言:javascript
复制
#lang racket

(define (interchange xs)
  (match xs
    [(or '() (list _))                 ; if the list is empty or has one element
     xs]                               ; then interchange keeps the original list
    [(list* x y more)                  ; if the list has two or more elements,
     (list* y x (interchange more))])) ; then the result consists of the two
;                                      ; first elements (with the order swapped)
;                                      ; followed by the result of 
;                                      ; interchanging the remaining elements.


(interchange '( ))                                 
(interchange '(a))                               
(interchange '(a  b))                              
(interchange '(a  b  c))                           
(interchange '(a  1  b  2  c  3  d  4))            
(interchange '(hello  you  -12.34  5  -6  enough)) 

输出:

代码语言:javascript
复制
'()
'(a)
'(b a)
'(b a c)
'(1 a 2 b 3 c 4 d)
'(you hello 5 -12.34 enough -6)
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/30202853

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档