【问题标题】:Using accumulator to concatenate a list of numbers使用累加器连接数字列表
【发布时间】:2021-01-13 15:32:14
【问题描述】:

我正在尝试创建一个函数来将整数列表连接成单个整数/字符串, 预期值:

(check-expect (concatNumbers (list 1 2 3 4)) 1234)
(check-expect (concatNumbers (list 0 4 3 2 1)) 04321)

我的功能:

(define (concatNumbers alon)
  (local
    ((define (inner list1 acc)
       (cond
         ((empty? list1) acc)
         (else
          ((string-append (number->string (first list1)) acc)
           (inner (rest list1) acc))))))
(inner alon "")))

但是有一个我无法理解的错误:

function call: expected a function after the open parenthesis, but received "3"

我试图找到以下值的测试:

(concatNumbers (list 1 5 7 8 9 3))

【问题讨论】:

  • 那是....不是串联。

标签: syntax conditional-statements scheme racket function-call


【解决方案1】:

每个cond 子句(我猜你使用的是中级学生语言)包含两件事:

  • 一个测试表达式,要么为真要么不为真,或者else,它始终为真;
  • 一个表达式,如果它是测试表达式为真的第一个子句,则将对其进行评估。

所以,看看你的else 子句:

(cond
  ...
  (else
   ((string-append (number->string (first list1)) acc)
    (inner (rest list1) acc))))

好的,表达方式是

((string-append (number->string (first list1)) acc)
 (inner (rest list1) acc))

所以,如果这在语言中是合法的(它会是完整的 Racket),它的意思是:

  1. 评估(inner (rest list1) acc)
  2. 评估(string-append (number->string (first list1)) acc),结果最好是一个程序;
  3. 根据 (1) 产生的值调用 (2) 产生的过程。

看起来不太对劲,是吗?首先,(string-append ... ...) 返回什么?我的猜测是“不是程序”。

相反,您可能想再次调用inner,并将附加的字符串作为其acc 参数。

(你还必须做一些其他事情才能得到正确的答案,但我会保留它,因为它很有趣。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-28
    • 1970-01-01
    • 2023-03-14
    • 2015-06-08
    • 2022-06-10
    • 1970-01-01
    相关资源
    最近更新 更多