Lisp - if语句各种动作

时间:2017-02-07 07:06:03

标签: lisp

这是我的lisp代码。

 (DEFUN F (A B)
              (SETF C (* 4 A))
              (SETF D (* 2 (EXPT B 3)))
              (SETF RES (+ C D))
              (IF (AND (TYPEP A 'INTEGER) (TYPEP B 'INTEGER))
                  (list 'Final 'value '= res)
                '(YOUR INPUTS ARE NOT NUMBERS)))

例如,(f 5 9)效果很好。 但(f 'w 'q)无法处理以下错误消息:

  

(ERROR TYPE-ERROR DATUM W预期类型数字格式控制             〜@< ~s' is not of the expected type〜S'〜:@> FORMAT论点             (W NUMBER))     错误:W' is not of the expected type NUMBER'

如果A,B是整数,我想制作4A + 2B ^ 3。

否则,如果至少有一个不是整数打印错误消息。

我尝试上面显示的代码。 但是如何使用if语句进行此错误处理?

1 个答案:

答案 0 :(得分:5)

首先,您应该使用LET or LET*来定义局部变量。

(defun f (a b)
  (let* ((c (* 4 a))           ; You need LET* instead of LET because
         (d (* 2 (expt b 3)))  ; RES depends on the previous variables.
         (res (+ c d)))
    (if (and (typep a 'integer) (typep b 'integer))
        (list 'final 'value '= res)
        '(your inputs are not numbers))))

实际问题是,在检查参数是否为整数之前,您正在进行计算。您应该在IF

中移动计算
(defun f (a b)
  (if (and (integerp a) (integerp b))
      (let* ((c (* 4 a))
             (d (* 2 (expt b 3)))
             (res (+ c d)))
        (list 'final 'value '= res))
      '(your inputs are not numbers)))

返回这样的列表有点奇怪。如果您打算将它们作为用户的输出,则应该打印消息并返回实际结果。

(defun f (a b)
  (if (and (integerp a) (integerp b))
      (let ((result (+ (* 4 a)
                       (* 2 (expt b 3)))))
        (format t "Final value = ~a~%" result)
        result)                                      ; Return RESULT or
      (format t "Your inputs are not integers.~%"))) ; NIL from FORMAT.

在大多数情况下,如果参数类型不正确,您应该发出错误信号。从执行计算的函数打印输出通常是一个坏主意。

(defun f (a b)
  (check-type a integer "an integer")
  (check-type b integer "an integer")
  (+ (* 4 a)
     (* 2 (expt b 3))))

(defun main (a b)
  (handler-case
      (format t "Final value = ~a~%" (f a b))
    ;; CHECK-TYPE signals a TYPE-ERROR if the type is not correct.
    (type-error () (warn "Your inputs are not integers."))))

(main 12 1)
; Final value = 50
;=> NIL
(main 12 'x)
; WARNING: Your inputs are not integers.
;=> NIL

Common Lisp条件系统还允许您使用重启来修复错误。 CHECK-TYPE建立了一个名为STORE-VALUE的重新启动,您可以调用该重新启动来为该地点提供正确的值。在这种情况下,它可能没有意义,但您可以使用1作为默认值。

(defun main (a b)
  (handler-bind ((type-error (lambda (e)
                               (store-value 1 e))))
    (format t "Final value = ~a~%" (f a b))))

(main 12 1)
; Final value = 50
;=> NIL
(main 12 'x)
; Final value = 50
;=> NIL

请注意,条件/错误处理程序会增加一些开销,因此对于性能关键函数,您可能不想使用它们,而是在调用函数之前检查您的参数。

(declaim (ftype (function (integer integer) integer) f))
(defun f (a b)
  (declare (optimize (speed 3) (safety 0) (debug 0)))
  (+ (* 4 a)
     (* 2 (expt b 3))))

(defun main (a b)
  (if (and (integerp a)
           (integerp b))
      (format t "Final value = ~a~%" (f a b))
      (warn "Your inputs are not integers.")))