Racket 参数数未定义的Lambda函数

Racket 参数数未定义的Lambda函数,racket,lambda,Racket,Lambda,我需要创建一个函数,它接受任意数量的argumnet并返回这些元素的逗号分隔字符串 例如 这就是我迄今为止所尝试的: (define (comma-separated-list x . xs) (begin (display x) (when (not (null? xs)) (begin (display " , ") (comma-separated-list xs))))) 但这是不正确的工作 例如: (comma-sepa

我需要创建一个函数,它接受任意数量的argumnet并返回这些元素的逗号分隔字符串

例如

这就是我迄今为止所尝试的:

(define (comma-separated-list x . xs)
  (begin
    (display x)
    (when (not (null? xs))
      (begin
        (display " , ")
        (comma-separated-list xs)))))

但这是不正确的工作

例如:

(comma-separated-list 1 2 3)
返回字符串:

1 , (2 3)
虽然我想让它返回:

1, 2, 3
如何实现它?

您的代码:

(define (comma-separated-list x . xs) ; (a) can accept any number of arguments
  (begin
    (display x)                       ; (b) print the first argument 
    (when (not (null? xs))
      (begin
        (display " , ")
        (comma-separated-list xs))))) ; (c) a call with just one argument
在第一次调用
(逗号分隔列表1 2 3)
之后,第
(c)
行上的递归调用相当于

(comma-separated-list '(2 3))
它只有一个参数,而不是两个参数。您需要将逗号分隔列表
改为剩余参数:

(apply comma-separated-list xs)
其他注释 顺便说一句,你所说的你想要的,你在期望的输出中显示的,以及你的代码将生成的,这两者之间是有区别的。你最初的例子是

(comma-separated-list 1 2 3)
;=> "1 , 2 , 3"
逗号前有空格,这就是你得到的

(display " , ")
但是在编辑中,你说你想要

1, 2, 3
很容易得到一个或另一个(只需调整空间),但要注意差异

您的代码:

(define (comma-separated-list x . xs) ; (a) can accept any number of arguments
  (begin
    (display x)                       ; (b) print the first argument 
    (when (not (null? xs))
      (begin
        (display " , ")
        (comma-separated-list xs))))) ; (c) a call with just one argument
在第一次调用
(逗号分隔列表1 2 3)
之后,第
(c)
行上的递归调用相当于

(comma-separated-list '(2 3))
它只有一个参数,而不是两个参数。您需要将逗号分隔列表
改为剩余参数:

(apply comma-separated-list xs)
其他注释 顺便说一句,你所说的你想要的,你在期望的输出中显示的,以及你的代码将生成的,这两者之间是有区别的。你最初的例子是

(comma-separated-list 1 2 3)
;=> "1 , 2 , 3"
逗号前有空格,这就是你得到的

(display " , ")
但是在编辑中,你说你想要

1, 2, 3

很容易得到一个或另一个(只需调整空间),但要注意差异

您只需使用
字符串连接

(define (comma-separated-list . lst)
  (string-join 
   (map (lambda (e) (format "~a" e)) lst) 
   ", "))
然后


您只需使用
字符串联接

(define (comma-separated-list . lst)
  (string-join 
   (map (lambda (e) (format "~a" e)) lst) 
   ", "))
然后


“这不能正常工作。”它在做什么?它在做什么?你期望它做什么?我根据你的建议编辑了这个问题“这不正常工作”。它在做什么?它在做什么?你期望它做什么?我根据你的建议编辑了这个问题,缩短了七个:
(define(comma-separated list.lst)(string-join(map~a-lst)”,“”)
甚至更短:
(define(comma-separated list.lst)(string-join(map~a-lst)”,“”)