Browse code
feat: add utilities to fwoar-functional-utils
- fwoar/eq: generic equality operator
- ==: curried equality
- applicable-when: apply function, if condition holds
- matches-regex: curried regex-matching predicate
- and: short-circuiting conjunction of predicate functions
- keys: extract a set of keys from a map
Showing 1 changed files
... | ... |
@@ -115,6 +115,39 @@ |
115 | 115 |
(lambda (key) |
116 | 116 |
(gethash key ht))) |
117 | 117 |
|
118 |
+(cl-defgeneric fwoar/eq (a b) |
|
119 |
+ (:method (a b) |
|
120 |
+ (eql a b)) |
|
121 |
+ (:method ((a string) (b string)) |
|
122 |
+ (equal a b))) |
|
123 |
+ |
|
124 |
+(fwoar/def-ns-fun == (v) |
|
125 |
+ (lambda (it) |
|
126 |
+ (fwoar/eq v it))) |
|
127 |
+ |
|
128 |
+(fwoar/def-ns-fun applicable-when (cond fn) |
|
129 |
+ (lambda (data) |
|
130 |
+ (when (funcall cond data) |
|
131 |
+ (funcall fn data)))) |
|
132 |
+ |
|
133 |
+ |
|
134 |
+(fwoar/def-ns-fun matches-regex (regex &optional start) |
|
135 |
+ (lexical-let ((regex regex)) |
|
136 |
+ (lambda (data) |
|
137 |
+ (if start |
|
138 |
+ (string-match-p regex data start) |
|
139 |
+ (string-match-p regex data))))) |
|
140 |
+ |
|
141 |
+ |
|
142 |
+(cl-defmacro fwoar/and (&rest fns) |
|
143 |
+ (let ((dat (gensym "dat"))) |
|
144 |
+ `(lambda (,dat) |
|
145 |
+ (and ,@(mapcar (lambda (fn) |
|
146 |
+ `(funcall ,fn ,dat)) |
|
147 |
+ fns))))) |
|
148 |
+ |
|
149 |
+;; TODO: think about whether the plist behavior here makes sense |
|
150 |
+;; should we require plists to have symbol keys? |
|
118 | 151 |
(cl-defgeneric fwoar/extract-key (map key) |
119 | 152 |
(:method ((map hash-table) key) |
120 | 153 |
(gethash key map)) |
... | ... |
@@ -123,12 +156,20 @@ |
123 | 156 |
(cons (cdr (cl-assoc key map :test 'equal))) |
124 | 157 |
(t (cl-loop for (a-key . value) on map by #'cddr |
125 | 158 |
when (equal key a-key) do |
126 |
- (return (car value))))))) |
|
159 |
+ (return (car value)))))) |
|
160 |
+ (:method ((map vector) (key number)) |
|
161 |
+ (elt map key))) |
|
127 | 162 |
|
128 | 163 |
(fwoar/def-ns-fun key (key) |
129 | 164 |
(lambda (map) |
130 | 165 |
(fwoar/extract-key map key))) |
131 | 166 |
|
167 |
+(fwoar/def-ns-fun keys (key &rest keys) |
|
168 |
+ (lambda (map) |
|
169 |
+ (cl-loop for key in (cons key keys) |
|
170 |
+ for cur = (fwoar/extract-key map key) then (fwoar/extract-key cur key) |
|
171 |
+ finally (return cur)))) |
|
172 |
+ |
|
132 | 173 |
(comment |
133 | 174 |
(fwoar/def-ns-fun regex-match (regex) |
134 | 175 |
(lambda (data) |