Lisp

Emacs Lisp Introduction for Python Programmers

emacs lisp tech python

This is a brief introduction to Emacs Lisp for Python programmers, (although I am not an Elisp expert, and actually I am more familiar with Python than Elisp). Both languages have quite different syntaxes, it is interesting to see how can implement Python code with lisp code.

The content follows the strucutre from Learn X in Y Minutes Where X is Python, and we will touch all the topics.

Primitive Datatypes and Operators

Numbers

Python

# Integer
1
# Float
3.14
# Math is what you would expect
1 + 1   # => 2
8 - 1   # => 7
10 * 2  # => 20
35 / 5  # => 7.0

# Integer division rounds down for both positive and negative numbers.
5 // 3       # => 1
-5 // 3      # => -2
5.0 // 3.0   # => 1.0  # works on floats too
-5.0 // 3.0  # => -2.0

# The result of division is always a float
10.0 / 3  # => 3.3333333333333335

# Modulo operation
7 % 3   # => 1
# i % j have the same sign as j, unlike C
-7 % 3  # => 2

# Exponentiation (x**y, x to the yth power)
2**3  # => 8

# Enforce precedence with parentheses
1 + 3 * 2    # => 7
(1 + 3) * 2  # => 8
Elisp

;; Integer
1
;; Float
3.14
;; Math is what you would expect
(+ 1 1)   ; => 2
(- 8 1)   ; => 7
(* 10 2)  ; => 20
(/ 35 5)  ; => 7

;; Integer division rounds down for both positive and negative numbers.
(truncate (/ 5 3))       ; => 1
(truncate (/ -5 3))      ; => -2
(truncate (/ 5.0 3.0))   ; => 1.0  ; works on floats too
(truncate (/ -5.0 3.0))  ; => -2.0

;; The result of division is always a float if the denominator or numerator is float
(/ 10.0 3)  ; => 3.3333333333333335

;; Modulo operation
(% 7 3)   ; => 1
;; different from Python
(% -7 3)  ; => -1

;; Exponentiation
(expt 2 3)  ; => 8

;; Enforce precedence with parentheses
(+ 1 (* 3 2))    ; => 7
(* (1+ 3) 2)  ; => 8

Bools and comparasion

In Emacs Lisp, booleans are represented by the symbols t for true and nil for false.