【问题标题】:How to force variables/inputs to be treated as different types in scheme?如何强制变量/输入在方案中被视为不同类型?
【发布时间】:2020-02-27 19:41:11
【问题描述】:

我正在尝试编写一个解析字符串并返回字符串中所有数字字符之和的递归方案函数。

我想我需要做这样的事情:

(define (sumNums s)
    (if (null? s) 1
        (if (char-numeric? (car s))
            (+ ((car s) (sumNums (cdr s))))
            (sumNums(cdr s)))))

每当我尝试使用字符串作为参数运行它时,它都会给我一个错误,说它需要一对。如何在函数中指示我将给它一个字符串?

此外,我无法将 (car s) 作为字符传递给 (char-numeric?) 过程。只需使用一个简单的示例函数:

(define (isDigit c)
    (if(char-numeric? c)
        (display "is a number")
        (display "is not a number")))

(isDigit #\5)

如果我在函数调用的输入之前明确包含#\,如上所述,它可以正常工作。但是函数中是否有任何方法可以强制将输入解释为字符?

(define (isDigit #\c)
    (if(char-numeric? c)
        (display "is a number")
        (display "is not a number")))

我尝试了上面的函数,它给出了未绑定 c 的错误。这个:

(isDigit #\(5))

也不行。所以在方案中,我什至不能强制将表达式 (5) 解释为字符 5?

非常感谢您的帮助,我刚开始学习方案,发现它非常不直观。

【问题讨论】:

    标签: types type-conversion scheme


    【解决方案1】:

    使用string->list 将您的输入字符串s 转换为字符列表:

    (define (sum-nums s)
      (let ((s (string->list s)))
        ...
    

    您还需要将数字字符转换为十进制数字,您需要(- (char->integer (car s)) (char->integer #\0))

    编辑:对不起。我错过了解决方案是递归的要求。您可能需要两个功能:

    (define (sum-digits str)
      (sum-digits-aux (string->list str) 0))
    

    第一个函数将字符串转换为字符列表,并调用起始和为 0 的辅助函数。第二个函数计算总和:

    (define (sum-digits-aux cs sum)
      (cond ((null? cs) ...)
            ((char-numeric? cs) ...)
            (else ...)))
    

    cond 有三个子句:第一个子句终止递归并返回结果;第二个子句处理数字字符;第三个子句处理非数字字符。

    我会留给你来填写。

    【讨论】:

    • 谢谢!我现在有一个扫描列表、检查字符和求和的函数。如何将它与 string->list 函数结合使用?我尝试将 sumList 函数放在您给出的 let 语句之后,我得到一个错误,即预期的数据类型是一对:(define (sumString s) (let ((s (string->list s)))) (if (null? s) ;;body of sumList function, works when called on its own 0 (if (char-numeric? (car s)) (+ (- (char->integer (car s)) (char->integer #\0)) (sumList (cdr s))) (sumList (cdr s)))))
    猜你喜欢
    • 2016-02-18
    • 2019-01-30
    • 1970-01-01
    • 2023-02-02
    • 2018-05-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-13
    相关资源
    最近更新 更多