Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions recipes/bind-optional-arguments.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Bind optional arguments

## Problem

You have a list, example from a function, and you want to simplify checking optional parameters with default values.

## Solution

```scheme
(define-syntax let-optionals
(syntax-rules ()
((_ expr ((v d) ... . tail) . body)
($let-optionals (v ...) () (d ...) () f tail expr body))))

(define-syntax $let-optionals
(syntax-rules ()

((_ () (vt ...) _ (cl ...) f tail expr body)
(letrec ((f (case-lambda cl ... ((vt ... . tail) . body))))
(apply f expr)))

((_ (vrf . vr*) (vt ...) (df . dr*) (cl ...) f . tailexprbody)
($let-optionals vr* (vt ... vrf) dr* (cl ... ((vt ...) (f vt ... df))) f . tailexprbody))))
```

Credit [@tallflier](https://www.reddit.com/user/tallflier/)

**NOTE**: this macro is requirement for base implementation of [SRFI-1](https://github.com/scheme-requests-for-implementation/srfi-1).

## Usage

```scheme
(define (calc num . rest)
(let-optionals rest ((multiplier 1) (factor 10))
(/ (* num multiplier) factor)))

(calc 10)
;; ==> 1
(calc 10 2)
;; ==> 2
(calc 10 2 5)
;; ==> 4
```
1 change: 1 addition & 0 deletions www-index.scm
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
(("Pairs and lists"
"create-k-combinations-from-list"
"bind-optional-arguments"
"find-depth-of-list"
"find-index-of-element-in-list"
"find-most-frequent-element-in-list"
Expand Down