Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Lisp is the function `1+` just syntactic sugar?

I just started learning Lisp. One of the first concepts to grasp seems to be the prefix notation (i.e. instead of writing "1 + 2", write "+ 1 2"). So I am trying to work out why the 1+ function exists.

What is the reason to prefer (+ 1 2) or (1+ 2)?

Is it just syntactic sugar? Is it for code optimisation? Is it for readability?

Perhaps there are more complex function call examples that show why the 1+ function exists. Any insight would be appreciated.

like image 850
Jeremy Larter Avatar asked Jun 19 '15 00:06

Jeremy Larter


2 Answers

Common Lisp the Language:

These are included primarily for compatibility with MacLisp and Lisp Machine Lisp. Some programmers prefer always to write (+ x 1) and (- x 1) instead of (1+ x) and (1- x).

Actually this goes back to the early Lisp. Lisp 1.5 from 1962 has it already. There the functions were called ADD1 and SUB1.

like image 55
Rainer Joswig Avatar answered Oct 23 '22 04:10

Rainer Joswig


Do remember that part of Common Lisp was standardizing what many implementations already had. So, if many implementations already had a 1+ function, that could have been enough to include it. Rainer's answer quotes CLtL2 on which implementations had it (MacLisp and Lisp Machine Lisp). But why would those implementations have had it in the first place? It's useful in loops, e.g.,

(do ((x 0 (1+ x)))
    ((= x 10))
  ; ...
  )

That's a place where (+ x 1) would have been fine, too. But there are lots of cases where it's handy to call that kind of function indirectly, and it's easier to (mapcar '1+ …) than to (mapcar (lambda (x) (+ 1 x)) …).

But that's really about it. Adding one (or subtracting one; there's 1- as well) to something is just such a common operation that it's handy to have a function to do it. If there's hardware support, it might be something the implementation can optimize, too. (Although the documentation does note that "implementors are encouraged to make the performance of [(1+ number) and (+ 1 number)] be the same.") Since these functions are available and widely used, they're a very good way to indicate the intent. E.g., you could make a typo and write (+ 1 x) when you meant to write (+ 2 x), but it's much less likely that you wanted to add two if you actually wrote (1+ x). These functions are idiomatic in Common Lisp (e.g., see How do I increment or decrement a number in Common Lisp?). Emacs Lisp also includes 1+ and 1-.

The language wouldn't suffer greatly if it weren't there, but it would be reimplemented many times by many different people. For instance, Racket implements add1 and sub1. (Also, see add1 function from scheme to R5RS.)

like image 20
Joshua Taylor Avatar answered Oct 23 '22 03:10

Joshua Taylor