mirror of
				https://github.com/janet-lang/janet
				synced 2025-10-30 23:23:07 +00:00 
			
		
		
		
	Add varfn.
This commit is contained in:
		| @@ -2,6 +2,7 @@ | |||||||
| All notable changes to this project will be documented in this file. | All notable changes to this project will be documented in this file. | ||||||
|  |  | ||||||
| ## Unreleased | ## Unreleased | ||||||
|  | - Add `varfn` macro | ||||||
| - Add compile time arity checking when function in function call is known. | - Add compile time arity checking when function in function call is known. | ||||||
| - Added `slice` to the core library. | - Added `slice` to the core library. | ||||||
| - The `*/slice` family of functions now can take nil as start or end to get | - The `*/slice` family of functions now can take nil as start or end to get | ||||||
|   | |||||||
| @@ -1538,6 +1538,30 @@ | |||||||
|     (set current (macex1 current on-binding))) |     (set current (macex1 current on-binding))) | ||||||
|   current) |   current) | ||||||
|  |  | ||||||
|  | (defmacro varfn | ||||||
|  |   "Create a function that can be rebound. varfn has the same signature | ||||||
|  |   as defn, but defines functions in the environment as vars. If a var 'name' | ||||||
|  |   already exists in the environment, it is rebound to the new function. Returns | ||||||
|  |   a function." | ||||||
|  |   [name & body] | ||||||
|  |   (def expansion (apply defn name body)) | ||||||
|  |   (def fbody (last expansion)) | ||||||
|  |   (def modifiers (tuple/slice expansion 2 -2)) | ||||||
|  |   (def metadata @{}) | ||||||
|  |   (each m modifiers | ||||||
|  |     (cond | ||||||
|  |       (keyword? m) (put metadata m true) | ||||||
|  |       (string? m) (put metadata :doc m) | ||||||
|  |       (error (string "invalid metadata " m)))) | ||||||
|  |   (with-syms [entry old-entry f] | ||||||
|  |     ~(let [,old-entry (,dyn ',name)] | ||||||
|  |        (def ,entry (or ,old-entry @{:ref @[nil]})) | ||||||
|  |        (,setdyn ',name ,entry) | ||||||
|  |        (def ,f ,fbody) | ||||||
|  |        (,put-in ,entry [:ref 0] ,f) | ||||||
|  |        (,merge-into ,entry ',metadata) | ||||||
|  |        ,f))) | ||||||
|  |  | ||||||
| ### | ### | ||||||
| ### | ### | ||||||
| ### Function shorthand | ### Function shorthand | ||||||
|   | |||||||
		Reference in New Issue
	
	Block a user
	 Calvin Rose
					Calvin Rose