schemedoc / cookbook

New Scheme Cookbook
https://cookbook.scheme.org
30 stars 3 forks source link

[Recipe] let-optionals #54

Closed lassik closed 3 years ago

lassik commented 3 years ago

Problem

Implement optional positional arguments in portable code (RnRS and syntax-rules).

https://github.com/ashinn/chibi-scheme/blob/master/lib/chibi/optional.scm

jcubic commented 3 years ago

@lassik Do you know maybe about something like destructuring-bind for Scheme? I wanted to create something like this for my Scheme that will also support vectors and objects (syntax based on JavaScript not part of R7RS).

Something like:

(let-bind ((#(fist . rest) #(1 2 3 4)) ;; I'm not sure if #(first . rest) will ever be valid syntax
           ((a . b) '(1 2 3)))
  (print (list first a)))

Macro like this would be very useful. The problem is that it needs to supper arbitrary nested patterns.

lassik commented 3 years ago

In Scheme, (match ...) is the closest semi-standard thing to desctructuring-bind. Unfortunately, there is no standard syntax for match. See e.g. SRFI 200 and 204, and the portable (chibi match) is available from http://snow-fort.org/pkg

lassik commented 3 years ago

(match ...) is very similar to the "pattern matching" feature in the ML language family (Standard ML, OCaml, Elm).

jcubic commented 3 years ago

I've asked this also on Reddit and someone provided a nice implementation using case-lambda. He agreed to use it in the cookbook:

https://www.reddit.com/r/scheme/comments/p8ovr7/how_to_define_letoptionals_macro_from_srfi1/

lassik commented 3 years ago

Neat! Can you make a PR to add it?