在Common Lisp中创建一个方法

时间:2016-10-15 18:43:40

标签: common-lisp clisp

您好我正在做一个条件,我只想调用一个方法,如果条件为真,问题是我找不到语法如何在C-Lisp中创建一个方法我在这里使用这种语言是新的'代码。

/* I want to create a method here which i can all anytime in my condition but I am having problem with a syntax 

 (void method()
   (print "Invalid")
 )

*/

(print "Enter number") 
(setq number(read())
(cond((< 1 number) (print "Okay"))
     ((> 1 number) /*I want to call a method here (the invalid one)*/ )
) 

1 个答案:

答案 0 :(得分:3)

要在常见的lisp中创建一个函数,您可以使用defun运算符:

(defun signal-error (msg)
   (error msg))

现在你可以这样称呼它:

(signal-error "This message will be signalled as the error message")

然后你可以在你的代码中插入它:

(print "Enter number") 
(setq number (read)) ;; <- note that you made a syntax error here.
(cond ((< 1 number) (print "Okay"))
      ((> 1 number) (signal-error "Number is smaller than 1."))))

在你的问题中,你问的是method。方法对类进行操作。例如,假设您有两个类humandog

(defclass human () ())
(defclass dog () ())

要为您使用defmethod的每个班级创建特定的方法:

(defmethod greet ((thing human))
  (print "Hi human!"))

(defmethod greet ((thing dog))
  (print "Wolf-wolf dog!"))

让我们为每个类创建两个实例:

(defparameter Anna (make-instance 'human))
(defparameter Rex (make-instance 'dog))

现在我们可以用同样的方法迎接每个生物:

(greet Anna) ;; => "Hi human"
(greet Rex)  ;; => "Wolf-wolf dog!"

知道执行哪种方法的常见lisp过程称为“动态调度”。基本上它将给定参数的类与defmethod定义匹配。

但我不知道你为什么需要代码示例中的方法。

如果我是你,我将如何编写代码:

;; Let's wrap the code in a function so we can call it
;; as much as we want
(defun get-number-from-user ()
  (print "Enter number: ")
  ;; wrapping the number in a lexical scope is a good
  ;; programming style. The number variable is not
  ;; needed outside the function.
  (let ((number (read)))
    ;; Here we check if the number satisfies our condition and
    ;; call this function again if not.
    (cond ((< number 1) (print "Number is less than 1")
                        (get-number-from-user))
          ((> number 1) (print "Ok.")))))

我建议你阅读“Lisp之地”。这对初学者来说很棒。