【问题标题】:Rewrite code to be with less procedures in Scheme重写代码以在 Scheme 中使用更少的程序
【发布时间】:2014-12-30 16:11:15
【问题描述】:

我写了一个程序,给定两个指定范围的数字,应该返回该范围内的数字的数量(计数),以octal 形式表示,由多个相同的数字组成。例如72->111 符合此条件,因为所有数字都相同。输出示例:

(hw11 1 8) -> 7,(hw11 1 9) -> 8,(hw11 1 18) -> 9,(hw11 1 65) -> 14,等等……

我的问题是,要正确,我的程序必须只定义 2 个程序,而目前我有更多的东西,不知道如何减少它们。因此,欢迎任何有关重写代码的帮助:)。代码如下:


(define (count-digits n)
  (if (<= n 0) 
      0 
      (+ 1 (count-digits (quotient n 10)))))

(define (toOct n)
  (define (helper n octNumber i)
    (if(<= n 0)
       octNumber
       (helper (quotient n 8) 
               (+ octNumber 
                  (* (expt 10 i) 
                     (remainder n 8)))
               (+ i 1))))
  (helper n 0 0))

(define (samedigits n)
  (define (helper n i)
    (if (<= n 0)
        #t 
        (if (not (remainder n 10) i))
        #f
        (helper (quotient n 10) i))))

(helper n (remainder n 10))
)

(define (hw11 a b)
  (define (helper a x count)
    (if (> a x)
        count
        (if (samedigits (toOct x))
            (helper a (- x 1) (+ count 1))
            (helper a (- x 1) count))))
  (helper a b 0))

【问题讨论】:

  • 你的代码没有编译,也没有格式化。
  • 如果没有正确的识别,LISP 代码是不可读的。现在你可以很容易地看到samedigits 有一些错误。一个括号是过早地结束内部。如果您使用带有括号匹配的 IDE 或编辑器,则不会发生这种情况。

标签: functional-programming scheme procedure


【解决方案1】:

您可能有限制,并且您没有说明您正在使用哪个 Scheme 实现;以下是在 Racket 和 Guile 上测试过的示例:

(define (hw11 a b)
  (define (iter i count)
    (if (<= i b)
        (let* ((octal (string->list (number->string i 8))) 
               (allc1 (make-list (length octal) (car octal))))
          (iter (+ i 1) (if (equal? octal allc1) (+ count 1) count)))
        count))
  (iter a 0))

测试:

> (hw11 1 8)
7
> (hw11 1 9)
8
> (hw11 1 18)
9
> (hw11 1 65)
14

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-06-22
    • 1970-01-01
    • 2018-03-07
    相关资源
    最近更新 更多