Skip to content

Instantly share code, notes, and snippets.

@candh
Created January 26, 2019 23:59
Show Gist options
  • Select an option

  • Save candh/e0567b465772c16c803e1d8af3d93333 to your computer and use it in GitHub Desktop.

Select an option

Save candh/e0567b465772c16c803e1d8af3d93333 to your computer and use it in GitHub Desktop.
Elisp cheatsheet.
;; from https://harryrschwartz.com/2014/04/08/an-introduction-to-emacs-lisp.html
43
3.0
"foo!"
;; FUNCTIONS
(+ 1 2 3 4 5)
;; LISt Processing Language
(1 2 3)
`(1 2 3)
(list 1 2 3 4 5)
;; "car" -- returns the first element of the list
(car
(list 1 2 3))
;; "cdr" -- returns the entire list except the first element
(cdr
`(1 2 3 4 5))
;; "cons" -- construct a list
(cons 1 `(2 3))
;; "append" -- takes two lists and joins them together
(append `(1 2) `(3 4))
;; VARIABLES
(setq my-list `(mac linux))
;; TODO: READ ABOUT MACROS IN ELISP
;; local variables
(let ((a 1)
(b 3))
(- a b))
;; FUNCTIONS
(defun main ()
"A docstring that tells a little bit about my function"
"Hello!")
(main)
(defun square (x)
(* x x))
(square 2)
;; CONDITIONALS
;; every value is truthy except nil and the empty list ()
;; and
(and t nil)
(and 1 13)
;; or
(or t nil)
(or nil `())
;; not
(not nil)
;; don't try to be very clever and try to write code
;; based on those return values that these functions give
;; unless you wanna dab on the haters
;; when -- only take an action if a predicate is true
(when (= (+ 2 2) 4)
"passed check")
;; if, else -- good ol' if else
(defun even-or-odd (n)
(if (= (% n 2) 0)
"even"
"odd"))
(even-or-odd 2)
(even-or-odd 54)
(even-or-odd 32343)
;; cond - much like a switch, i think
;; takes in a "collection" of lists. Remember that.
;; like "let"
(defun pick-sword (n)
(cond
((= n 0) "Wood")
((= n 1) "Plastic")
((= n 2) "Gold")))
(pick-sword 2)
;; anonymous functions -- lambdas!
;; lambdas are function literals
(lambda (x) (+ x 5))
;; call it
((lambda (x) (+ x 5)) 9)
;; funcall -- calls a function
(funcall (lambda (x) (* x x)) 4)
(funcall '+ 1 2)
;; store the lambda in a variable
(fset `square (lambda (x) (* x x)))
(square 3)
;; HIGHER ORDER FUNCTIONS
(defun transform-until-zero (fn n)
"transforms n with the function given unless the number is 0"
(if (= n 0)
0
(funcall fn n)))
(transform-until-zero (lambda (n) (* n 2)) 0)
(transform-until-zero (lambda (n) (* n 2)) 3)
;; a very important higher order function is mapcar
;; takes in a list and a function and applies the function
;; to every element in the list. NOW we're talking
;; much like map in JS
(mapcar (lambda(n) (+ n 1)) '(1 2 3))
;; non destructive!
(setq my-list '(1 2 3))
(mapcar (lambda (n) (+ n 1)) my-list)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment