function factory in elisp

Table of Contents

1. example

return a predicate function taking 1 argument. if it is in [left,right], it will return true, otherwise fallse For example, (setq in2-3 (in-region-p-c 2 3)), then (in2-3 2.5) returns ture. [2023-05-26 Fri 13:45]

(defun hermanhel-in-region-p-c (left right)
  `(lambda (val) (< ,left val ,right))
                )
(setq in2-3 (hermanhel-in-region-p-c 2 3))
(fset 'in2-3 (hermanhel-in-region-p-c 2 3))


;; ((lambda (val) (< 2 val 3)) 2.5)
;; this works

(in2-3 2.5)
;; this won't work if not using fset

(funcall 'in2-3 2.5)
;; this would work either way(setq or fset)

note - to plug values in lambda, make a function generator, use ` and , as lambda is macro and every symbol is treated as symbol only, without evaluation note - to use function produced by factory:

  • if used with (funcall in2-3 2.5), define with (setq in2-3 (in-region 2 3))
  • if used with (in2-3 2.5), define with (fset in2-3 (in-region 2 3))

note - defmacro if you don’t want some part of argument to be evaluated1, defun if it does not matter when the calculation is done

Backlinks

reference retrivial time counts in critical recall time

Say your critical recall time is 3 minutes, and you want to use a specific programming pattern, like function factory in elisp. It is possible that you can’t recall all critical points for writing function factory in elisp(using fest, using ` and ,, when to use defmacro, when to use defun), but if you can retrieve the reference and finish reading it in 3 minutes, you should be able to use that piece of knowledge with no friction

Footnotes:

1

or evaluated as lisp symbols: this is the case with loop, when there’s bunch of symbols like for and to that if interpretated as lisp symbols will produce symbol-not-defined error.

Author: Linfeng He

Created: 2024-04-03 Wed 23:25