Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 96 lines (72 sloc) 2.212 kb
5378653 sroccaserra Added tools.el
authored
1 ;;
2 ;; Various tool functions & macros
3 ;;
4
5 (defmacro comment (&rest body)
6 "Ignores body, yields nil"
7 nil)
8
9 ;;;;;;;
10 ;; Math
11
12 (defun mean (values)
13 (/ (reduce '+ values)
14 (float (length values))))
15
16 (defun square (x)
17 (* x x))
18
19 (defun variance (values)
20 (- (->> values (mapcar 'square) mean)
21 (square (mean values))))
22
23 ;;;;;;;;;;;;
24 ;; Sequences
25
26 (defun sequence (maybe-seq)
27 "Returns the value wrapped in a sequence if it is not a sequence already."
28 (if (sequencep maybe-seq) maybe-seq
29 (list maybe-seq)))
30
31 (defun random-elt (sequence)
32 (elt sequence
33 (-> sequence length random)))
34
35 (defun seq-difference (lseq rseq)
36 (remove-if (lambda (element) (find element rseq :test 'equal))
37 lseq))
38
39 ;;;;;;;;;;
40 ;; Strings
41
42 (defun string-empty-p (str)
3b1da06 sroccaserra small tool changes
authored
43 (if str
44 (string= "" str)
45 t))
5378653 sroccaserra Added tools.el
authored
46
3b1da06 sroccaserra small tool changes
authored
47 (defun string-not-empty-p (str)
48 (not (string-empty-p str)))
5378653 sroccaserra Added tools.el
authored
49
50 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
51 ;; Undestructive alist functions
52
53 (defun alist-get (alist key &optional default)
54 (or (assoc-default key alist)
55 default))
56
57 (defun alist-remove (alist key)
58 "Doesn't change the original alist, returns a new one instead."
59 (remove-if (lambda (x) (equal key (car x)))
60 alist))
61
62 (defun alist-set (alist key value)
63 "Doesn't change the original alist, returns a new one instead."
64 (cons (cons key value) (alist-remove alist key)))
65
66 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;
67 ;; Clojure's Trush operators
68
69 (defmacro -> (result &rest body)
70 (dolist (form body result)
71 (setq form (sequence form)
72 result (append (list (car form) result)
73 (cdr form)))))
74
75 (defmacro ->> (result &rest body)
76 (dolist (form body result)
77 (setq form (sequence form)
78 result (append form (list result)))))
79
80 ;;;;;;;;;;;;;;;;;;;;
81 ;; Functional tools
82
83 (defmacro partial (f &rest args)
84 `(lambda (&rest more)
85 (apply ',f ,@args more)))
86
87 (defmacro lexdef (name args &rest body)
88 "Defun with lexically-scoped parameters. Could also be called lexical-defun."
89 `(defun ,name ,args
90 (lexical-let ,(->> args
91 (remove-if (partial equal '&rest))
92 (mapcar (lambda (arg) (list arg arg))))
93 ,@body)))
94
95 (provide 'tools)
Something went wrong with that request. Please try again.