LISP - 检查Roman Numeral Converter是否有效的罗马数字

时间:2016-11-09 20:32:24

标签: validation lisp common-lisp

我有一个将罗马数字转换为十进制形式的lisp程序。它适用于有效输入,但我不知道如何检查输入是否是有效的罗马数字。目前,当给出无效输入(“MIM”)时,它仍会尝试错误地转换它。我需要它来代替返回ERROR消息。

(defun mapRomanToDecimal (chars nums string)
  (loop as char across string
        as i = (position char chars)
        collect (and i (nth i nums))))

(defun parseThroughRoman (R)
  (loop with nums = (mapRomanToDecimal "IVXLCDM" '(1 5 10 50 100 500 1000) R)
    as (A B) on nums if A sum (if (and B (< A B)) (- A) A)))

(defun romanToDecimal (RomanNumeral)
    (format t "~d~%" (parseThroughRoman (numlist-to-string RomanNumeral))))

(defun numlist-to-string (lst)
  (when lst
     (concatenate 'string 
             (write-to-string (car lst)) (numlist-to-string (cdr lst)))))


(romanToDecimal '(C D V)) -> 405
(romanToDecimal '(M I M)) -> 1999

1 个答案:

答案 0 :(得分:2)

关于风格......

  • 通常不需要数据类型转换
  • 代码可以更容易更通用

示例:

(defvar *roman-chars* "IVXLCDM")
(defvar *roman-nums*  '(1 5 10 50 100 500 1000))

(defun roman-numeral-to-decimal (roman-numeral)
  (let ((i (position (coerce roman-numeral 'character) *roman-chars*)))
    (and i (nth i *roman-nums*))))

(defun map-roman-numerals-to-decimal (roman-numerals)
  (map 'list #'roman-numeral-to-decimal roman-numerals))

(defun roman-to-decimal (roman)
  (loop as (A B) on (map-roman-numerals-to-decimal roman)
        if A sum (if (and B (< A B)) (- A) A)))

这意味着您可以将它与符号/字符/字符串,字符串,矢量符号/字符/字符串列表一起使用:

CL-USER 20 > (roman-to-decimal '(C D V))
405

CL-USER 21 > (roman-to-decimal '("C" "D" "V"))
405

CL-USER 22 > (roman-to-decimal '(#\C #\D #\V))
405

CL-USER 23 > (roman-to-decimal "CDV")
405

CL-USER 24 > (roman-to-decimal #(c d v))
405