方案 - 如何将数据结构应用于组合 2 个罗马数字对象(字母和值)以生成 2 个字符的罗马数字?

Scheme - How do you apply data structures to the combining of 2 Roman Numeral objects (letters & values) to produce a 2-character Roman Numeral?

我正在尝试解决以下问题:

Write a function called form-rn that consumes two Roman-Numeral objects (digit1 and digit2) and produces the two-character Roman-Numeral represented by the values of digit1 and digit2 read from left to right. The string values of digit1 and digit2 must be a single letter (one of I, V, X, L, C, D, or M).

For example:

(form-rn (make-Roman-numeral "C" 100) (make-Roman-numeral "C" 100)) 

produces (make-Roman-numeral "CC" 200), and

(form-rn (make-Roman-numeral "X" 10) (make-Roman-numeral "L" 50))

produces (make-Roman-numeral "XL" 40).

到目前为止我尝试了一些东西:

(define II (make-Roman-numeral "II" 2))
(define IV (make-Roman-numeral "IV" 4))

这是为了生成罗马数字组合,但我意识到这可能不是我应该采用的方法。

(make-Roman-numeral 'I 1)
(make-Roman-numeral 'V 5)

我想也许我必须分别定义每个罗马数字,但它不应该是像“I”这样的单个字符,它应该是像“IV”这样的组合

(define (form-rn digit1 digit2)
  (cond
    [(> digit1 digit2) (+ (Roman-numeral-value digit1) (Roman-numeral-value digit2))]))

我考虑过设置条件,因为问题说如果第一个符号大于另一个,则两个符号相加,但如果第二个符号大于第一个,则较大符号的值减去较小符号的值。

您最后一次尝试绝对是在正确的轨道上!一些注意事项

  1. 问题要求您从 form-rn 函数中 return 一个 Roman-numeral 对象,因此您需要从其中调用 make-Roman-numeral
  2. 你需要分别处理digit1大于digit2和倒数的情况。

为了将字母相加,我们可以使用string-append。要找到新的 value,那么我们可以使用 cond 来检查哪个数字更大。然后,我们只需要将计算出的两个新值组合成一个新的 Roman-numeral 对象即可。

您可以这样做:

(define (form-rn digit1 digit2)
  (define new-letters (string-append (Roman-numeral-letters digit1) (Roman-numeral-letters digit2)))
  (define new-values
    (let ([value1 (Roman-numeral-value digit1)]
          [value2 (Roman-numeral-value digit2)])
      (cond
        [(> value1 value2)
         (+ value1 value2)]
        [else
         (- value2 value1)])))
  (make-Roman-numeral new-letters new-values))