【问题标题】:Creating a method in Common Lisp在 Common Lisp 中创建方法
【发布时间】:2016-10-15 18:43:40
【问题描述】:

嗨,我正在做一个条件,如果条件为真,我只想调用一个方法,问题是我找不到如何在 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)*/ )
) 

【问题讨论】:

  • void 应该做什么?函数见defmethoddefun的方法(没有类型重载)
  • 我还建议您查看条件系统。这是一个让您入门的链接gigamonkeys.com/book/…
  • Davids 的评论是关于实际的 lisp 条件,这与其他语言中的例外情况类似,但功能更强大。我发现您可能已经知道一种编程语言,也许是 C 系列语言之一。很难吸收你的第一个关于 algol 知识的口齿不清,所以最好玩绿色并立即去学习教程或书籍。
  • 数字为一时会发生什么?
  • @Sywester - 同意。 OP 应该考虑像 Practical Commmon Lisp 或类似的教程。

标签: common-lisp clisp


【解决方案1】:

要在 common 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!"

common 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 之国”。这是一本适合初学者的好书。

【讨论】:

  • 是的,但是在cond 测试之后已经有一个隐含的progn 所以这个是多余的。此外,您可能需要finish-output 以确保在要求输入之前显示提示。
  • 谢谢!当您尝试帮助其他人学习东西时,学习东西也很好!我更正了progn。我现在将熟悉finish-output
  • 我有时也会遇到这种情况,确实有帮助。
  • 您的意思是defclass 而不是class
  • 哎呀。已更正。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多