Add Two Number Code Using Lisp

7 min read

Add Two Number Code Using Lisp: A Beginner’s Guide to Lisp Arithmetic

Lisp is one of the oldest and most powerful programming languages, known for its distinctive parenthesized syntax and its ability to treat code as data. If you are just starting your journey with Lisp, one of the first things you will want to learn is how to perform basic arithmetic operations, such as adding two numbers. Which means this article will walk you through everything you need to know about writing add-two-number code in Lisp, from the fundamental syntax to more advanced concepts like recursion and variable binding. By the end, you will not only know how to add two numbers in Lisp but also understand why Lisp’s approach to arithmetic is both elegant and logical.

Understanding Lisp Syntax: Prefix Notation and Parentheses

Before diving into the actual code, Make sure you understand how Lisp expressions are structured. It matters. On the flip side, g. , 2 + 3), Lisp uses prefix notation. In real terms, unlike most programming languages that use infix notation (e. This means the operator comes first, followed by its operands, all enclosed in parentheses Simple as that..

(+ 2 3)

The plus sign + is the function (or operator), and 2 and 3 are its arguments. Consider this: the entire expression is wrapped in parentheses, which tells Lisp to evaluate it as a function call. This uniform syntax is one of the reasons Lisp is so powerful: everything is a list, and lists are evaluated in the same way Turns out it matters..

When you enter (+ 2 3) into a Lisp interpreter, it returns 5. Which means the interpreter first reads the list, then evaluates it by applying the function + to the arguments 2 and 3. This might feel strange at first, especially if you are used to languages like Python or Java, but with a little practice, prefix notation becomes second nature Easy to understand, harder to ignore..

The Basic Addition Operation in Lisp

The simplest way to add two numbers in Lisp is to use the built-in + function. You can pass any number of arguments to +, not just two. For instance:

(+ 1 2 3 4)

This expression returns 10. Still, for the specific task of adding two numbers, you can simply write:

(+ 10 20)

This returns 30. You can also nest expressions, which is where Lisp truly shines. Consider this example:

(+ 5 (* 2 3))

Here, Lisp first evaluates (* 2 3) to get 6, then adds 5 to it, resulting in 11. This ability to compose complex expressions from simple ones is a core feature of Lisp.

Defining a Custom Function to Add Two Numbers

While using + directly is straightforward, you will often want to create your own function that adds two numbers. This is especially useful when you need to reuse the same logic multiple times. In Lisp, you define a function using the defun macro That's the part that actually makes a difference..

(defun add-two (a b)
  (+ a b))

Let’s break this down:

  • defun is the Lisp macro for defining a function. In real terms, - (a b) is the parameter list, meaning the function expects two arguments. - add-two is the name of the function.
  • The body of the function is (+ a b), which adds the two parameters together.

Once defined, you can call add-two just like any other Lisp function:

(add-two 15 27)

This returns 42. You can also use your custom function inside larger expressions:

(* (add-two 3 4) 2)

This first computes (add-two 3 4) to get 7, then multiplies by 2 to get 14.

Using let to Bind Local Variables

Sometimes you need to store intermediate values while performing calculations. Consider this: lisp provides the let special operator for this purpose. With let, you can bind variables to values locally, making your code cleaner and more readable.

No fluff here — just what actually works.

(let ((x 8)
      (y 12))
  (+ x y))

In this example, x is bound to 8, y is bound to 12, and the body (+ x y) returns 20. The bindings are only valid within the let block, so they do not affect anything outside. This is particularly useful when you have complex calculations that require multiple steps Simple, but easy to overlook..

Not obvious, but once you see it — you'll see it everywhere And that's really what it comes down to..

Adding Different Types of Numbers in Lisp

Lisp supports various numeric types, including integers, floating-point numbers, rationals, and even complex numbers. The + function works without friction across all these types. For example:

(+ 1.5 2.5)   ; returns 4.0 (a floating-point number)
(+ 1/2 1/4)   ; returns 3/4 (a rational number)
(+ #c(1 2) #c(3 4)) ; returns #c(4 6) (a complex number)

Notice that when you mix integers and floats, Lisp automatically promotes the result to a float to preserve precision. This is called numeric contagion. Understanding how Lisp handles different number types is crucial when you start writing more advanced programs Less friction, more output..

Recursive Addition: A Deeper Look at Lisp’s Power

Probably most elegant aspects of Lisp is its support for recursion. Instead of using loops, Lisp programmers often write recursive functions. You can even implement addition recursively without using the + operator, using the built-in 1+ (increment) and 1- (decrement) functions.

(defun recursive-add (a b)
  (if (zerop b)
      a
      (recursive-add (1+ a) (1- b))))

Let’s understand how this works:

  • The function checks if b is zero using (zerop b).
  • If b is zero, it returns a (since adding zero to a gives a).
  • Otherwise, it calls itself with a incremented by one and b decremented by one.

Take this: (recursive-add 3 4) proceeds as follows:

  1. `(recursive-add

  2. (recursive-add 3 4)b is not zero, so call (recursive-add 4 3)

  3. (recursive-add 4 3)b is not zero, so call (recursive-add 5 2)

  4. (recursive-add 5 2)b is not zero, so call (recursive-add 6 1)

  5. (recursive-add 6 1)b is not zero, so call (recursive-add 7 0)

  6. (recursive-add 7 0)b is zero, return 7

The final result propagates back up the call stack, yielding 7. But while this linear recursion is conceptually simple, it consumes stack space proportional to b. For large numbers, this risks a stack overflow Worth keeping that in mind..

This is where a lot of people lose the thread.

(defun tail-recursive-add (a b)
  (labels ((helper (acc count)
             (if (zerop count)
                 acc
                 (helper (1+ acc) (1- count)))))
    (helper a b)))

Here, the inner helper function carries an accumulator (acc). Because the call to helper is in the tail position, a compliant Common Lisp implementation will compile this to iterative machine code, running in constant stack space regardless of the magnitude of b Worth knowing..

Higher-Order Functions and reduce

Lisp’s treatment of functions as first-class citizens allows for powerful abstractions. If you have a list of numbers to sum, you don't need to write an explicit loop or recursion; you can use reduce with the + operator:

(reduce #'+ '(10 20 30 40))  ; returns 100

reduce applies the function cumulatively to the elements of the sequence. This functional style is declarative—you describe what you want (a reduction via addition) rather than how to iterate. Combined with mapcar or remove-if-not, you can build complex data processing pipelines concisely:

;; Sum only the even numbers from a list
(reduce #'+ (remove-if-not #'evenp '(1 2 3 4 5 6 7 8))) ; returns 20 (2+4+6+8)

Conclusion

From the simple prefix notation of (+ a b) to the definition of custom functions, the management of local state with let, the seamless handling of a rich numeric tower, and the expressive power of recursion and higher-order functions, Lisp offers a uniquely unified environment for numerical computation. Worth adding: whether you are prototyping a mathematical algorithm, processing financial data with exact rationals, or exploring the theoretical foundations of computation via recursive definitions, the language gets out of your way and lets the mathematics speak for itself. Mastering these fundamentals provides not just a toolkit for addition, but a foundation for thinking about problems structurally and recursively—the hallmark of the Lisp approach Less friction, more output..

Out This Week

Just Went Live

For You

Other Angles on This

Thank you for reading about Add Two Number Code Using Lisp. We hope the information has been useful. Feel free to contact us if you have any questions. See you next time — don't forget to bookmark!
⌂ Back to Home