我有一个将罗马数字转换成十进制形式的lisp程序它对有效输入很有用,但是我不确定如何检查输入是否是有效的罗马数字例如,当前当给定一个无效输入(“MIM”)时,它仍然试图错误地转换它我需要它返回一个错误信息。

(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

最佳答案

一点点关于风格。。。
通常不需要进行数据类型转换
代码很容易变得更通用
例子:

(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

关于validation - LISP-检查罗马数字转换器是否有效的罗马数字,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40515523/

10-10 13:50