Search code examples
common-lispclisp

Creating a method in Common Lisp


Hi I am doing a condition which I just want to call a method if the condition is true, the problem is I cannot find the syntax how to create a method in C-Lisp I am new with this language here's the code.

/* 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)*/ )
) 

Solution

  • To create a function in common lisp you can use the defun operator:

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

    Now you can call it like so:

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

    Then you can insert it in your code like this:

    (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."))))
    

    In your question you are asking about a method. Methods operate on classes. For example imagine you have two classes human and dog:

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

    To create a method specific for each class you use defmethod:

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

    Let's create two instances for each class:

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

    Now we can greet each living being with the same method:

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

    The process of common lisp knowing which method to execute is called "Dynamic dispatch". Basically it matches the given argument's classes to the defmethod definitions.

    But I have no idea why you need methods in your code example.

    Here is how I would write the code if I was you:

    ;; 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.")))))
    

    I would suggest you read "The Land of Lisp". It is great book for beginners.