Skip to content
jrm-code-projectPublic

About

Named lambda and named let macros.

Resources

Stars

3 stars

Watchers

1 watching

Forks

Latest commit

 

History

11 Commits

Folders and files

Repository files navigation

named-let

Scheme-inspired binding macros for Common Lisp: named-let, named-lambda, letrec, letrec*, flambda, a Lisp-1 style define, and an extended let. No dependencies.

Overview

The library brings some of Scheme's binding forms to Common Lisp, making local recursion and self-reference concise.

Macro Purpose
let Extended let: optional name for recursion, _ ignored bindings, multi-form inits
named-let Scheme-style named let (same as let with a name)
named-lambda A lambda that can call itself by name; _ arguments are ignored
letrec Recursive bindings, initialized simultaneously
letrec* Recursive bindings, initialized sequentially
flambda A lambda whose parameters are callable as functions
define Top-level Scheme-style definition in a single (Lisp-1) namespace

Installation

Clone the repository into your Quicklisp local projects directory:

git clone https://github.com/jrm-code-project/named-let.git ~/quicklisp/local-projects/named-let

Then load it:

(ql:quickload "named-let")
;; or
(asdf:load-system "named-let")

Usage

Importing the package

The package NAMED-LET shadows COMMON-LISP:LET, so shadowing-import it to use the extended let:

(defpackage "MY-PACKAGE"
  (:shadowing-import-from "NAMED-LET" "LET")
  (:use "COMMON-LISP" "NAMED-LET"))

If you do not want to replace let, simply (:use "COMMON-LISP" "NAMED-LET") without the shadowing import and use named-let for the named form. (The exported symbols are define, flambda, letrec, letrec*, named-lambda, and named-let; let is imported explicitly as above.)


let

let accepts the standard syntax, plus three extensions.

Named let

A symbol before the binding list names a function that re-enters the let with new values:

(let foo ((x 22)
          (y 13))
  (if (zerop x)
      y
      (foo (- x 1) (+ y 1))))
;; => 35

The init forms are evaluated outside the scope of the name, as in Scheme:

(cl:let ((n 1))
  (let n ((m (1+ n))) m))   ; the init (1+ n) sees the outer N
;; => 2

A named let with no bindings is a thunk call: (let thunk () 42) => 42.

Ignored bindings with _

A binding of the symbol _ is replaced by a fresh uninterned symbol and an ignore declaration for it is added at the start of the body. The init form is still evaluated, so this is useful for side effects. Any number of _ bindings may appear.

(let ((a 22)
      (_ (format t "foo"))
      (b (sqrt 2))
      (_ (format t "bar")))
  body)

;; expands to
(let ((a 22)
      (#:ignore-1 (format t "foo"))
      (b (sqrt 2))
      (#:ignore-2 (format t "bar")))
  (declare (ignore #:ignore-1 #:ignore-2))
  body)

_ is matched by name, so it works from any package. Bare _ and (_) are allowed too (bound to nil and ignored). The same applies to _ bindings in a named let, and to _ parameters in named-lambda. A user declare at the start of the body is fine alongside the generated one.

Multiple forms in a binding

If a binding has more than one init form they are wrapped in a progn; the last value is bound:

(let ((a (format t "binding a") (+ 2 (sqrt x))))
  (+ a b))

;; expands to
(let ((a (progn (format t "binding a") (+ 2 (sqrt x)))))
  (+ a b))

As in standard Lisp, a bare variable y or (z) is bound to nil, and bindings are made in parallel (init forms do not see the new variables).

Malformed bindings (such as (let ((1 2)) 3)) signal an error at macroexpansion time.


named-let

(named-let name bindings . body) is equivalent to (let name bindings . body) and works without shadowing let.

(named-let recur ((items '(1 2 3 4 5))
                  (passing '())
                  (failing '()))
  (cond ((consp items)
         (if (evenp (car items))
             (recur (cdr items) (cons (car items) passing) failing)
             (recur (cdr items) passing (cons (car items) failing))))
        ((null items) (values passing failing))
        (t (error "Dotted tail on items."))))
;; => (4 2), (5 3 1)

Self-calls in tail position are compiled as loops by implementations that optimize tail calls, so deep iteration is fine:

(named-let tally ((i 0))
  (if (< i 100000) (tally (1+ i)) i))
;; => 100000

Choosing a name

Any symbol works, but when the name just means "go around again" a short name such as next or l can read well:

(named-let next ((i 0) (acc '()))
  (if (= i 5)
      (nreverse acc)
      (next (1+ i) (cons (* i i) acc))))
;; => (0 1 4 9 16)

loop cannot be used as the name: COMMON-LISP already binds that symbol (as a macro), and implementations such as SBCL lock the package against redefinition. The same applies to other COMMON-LISP symbols like count.


named-lambda

(named-lambda name lambda-list . body) returns a function that can call itself through name. A docstring at the start of the body is supported, and parameters named _ (or (_ default) in &optional/&key lists) are replaced by ignored gensyms.

(map 'list (named-lambda fact (x)
             (if (zerop x)
                 1
                 (* x (fact (1- x)))))
     '(7 11 2))
;; => (5040 39916800 2)

(funcall (named-lambda second-arg (_ x _) x) 1 3 2)
;; => 3

letrec and letrec*

Both bind variables so that init forms (usually lambdas) can refer to the variables, including each other. Variables bound by them can be called directly in function position, as in Scheme, as well as passed with funcall.

letrec evaluates all init forms and then assigns the variables simultaneously. It is suited to (mutually) recursive functions:

(letrec ((even? (lambda (x) (or (zerop x) (odd? (1- x)))))
         (odd?  (lambda (x) (and (not (zerop x)) (even? (1- x))))))
  (list (even? 22) (even? 7)))
;; => (T NIL)

(letrec ((fact (lambda (x) (if (zerop x) 1 (* x (fact (1- x)))))))
  (fact 5))
;; => 120

letrec* assigns sequentially, so each init form may use the earlier variables' values immediately:

(letrec* ((a (lambda () 1))
          (b (lambda () (+ (a) 2)))
          (c (lambda () (+ (a) (b) 2))))
  (c))
;; => 6

The variables are also ordinary values, so (funcall f 2) works too.


flambda

flambda builds a lambda whose parameters are bound in the function namespace, so they can be called without funcall:

(funcall (flambda (f) (f 3 4)) #'+)       ; => 7
(funcall (flambda (f) (f 1 2)) #'list)    ; => (1 2)

define

define is a Scheme-style top-level definition. The function is stored in the symbol's value cell, and a macro of the same name expands to a funcall of that value, so the name can be used in both value and function position.

;; function syntax, with optional docstring
(define (add-42 x) "Add x and 42." (+ x 42))
(add-42 1)                       ; => 43

;; value syntax
(define twice (lambda (f x) (funcall f (funcall f x))))
(twice #'1+ 2)                   ; => 4

;; recursion
(define (fact n) (if (zerop n) 1 (* n (fact (1- n)))))
(fact 5)                         ; => 120

Caveat: define only works at top level and is not a replacement for defun.


Integration with series

Macros in this library are aware of the series package: if it is loaded, expansions use the series definitions of let and funcall (when they exist); otherwise they use common-lisp. To use both libraries, shadow the additional symbols:

(defpackage "MY-PACKAGE"
  (:shadowing-import-from "NAMED-LET" "LET")
  (:shadowing-import-from "SERIES" "DEFUN" "FUNCALL" "LET*" "MULTIPLE-VALUE-BIND")
  (:use "COMMON-LISP" "NAMED-LET" "SERIES"))

Testing

Tests use FiveAM:

(asdf:test-system "named-let-test")
;; or
(ql:quickload "named-let-test")
(named-let-test:run-tests)

Avoid names locked by the implementation (such as loop or count) as named-let names; for example SBCL package locks reject them.


Contributing

Contributions are welcome! Please submit issues or pull requests on the GitHub repository.


License

This project is licensed under the MIT License. See the LICENSE file for details.

About

Named lambda and named let macros.

Resources

Stars

3 stars

Watchers

1 watching

Forks

Releases

Packages

Contributors

Languages