Search code examples
syntaxlispcommon-lisp

Lisp: IF condition using AND operator


I making this function.

(f 3 4) (sum = 7) 
(f 'a 'b) (not num!) 

My problem is how can I make if condition using and operator.

I try....

  1. (IF (and (typep a 'integer) (typep b 'integer)) (1) (0))

  2. (IF (and ((typep a 'integer)) ((typep b 'integer))) (1) (0))

  3. (IF ((and ((typep a 'integer)) ((typep b 'integer)))) (1) (0))

But it doesn't work. (1) and (0) is used temporarily.

Could I get some lisp syntax help?


Solution

  • The most important thing you need to learn about Lisp at this moment is that parens matter.

    In C you can write 1+3, (1)+3, (((1+3))) and they all mean the same thing. In lisp they are very very different:

    • a means "the value of the variable named a".
    • (a) means "the return value of the function named a called without any arguments".
    • ((a)) is a syntax error (but see PPS)

    So, every version with ((...)) is outright wrong.

    Since there is no function named 1, the first version is no good either.

    What you need is:

    (if (and (typep a 'integer)
             (typep b 'integer))
        1
        0)
    

    Note formatting and indentation. Lispers read code by indentation, not parens, so proper indentation is critical. Note that Emacs (and maybe some other Lisp-specific IDEs) will indent lisp code for you.

    PS. The description of what you are trying to accomplish is unclear, but it might be that the easiest way is to use generic functions:

    (defgeneric f (a b)
      (:method ((a integer) (b integer))
        (+ a b)))
    (f 1 2)
    ==> 3
    (f 1 'a)    
    *** - NO-APPLICABLE-METHOD: When calling #<STANDARD-GENERIC-FUNCTION F> with
          arguments (1 A), no method is applicable.
    

    PPS. Eventually you will see legitimate ((...) ...), e.g., cond:

    (defun foo (a)
      (cond ((= a 1) "one")
            ((= a 2) "two")
            (t "many")))
    (foo 1)
    ==> "one"
    (foo 3)
    ==> "many"
    

    or lambda forms:

    ((lambda (x) (+ x 4)) 5)
    ==> 9
    

    but you do not need to worry about those yet.