Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Destructuring function arguments #1936

Closed
peaceamongworlds opened this issue Jan 10, 2021 · 1 comment · Fixed by #1940
Closed

Destructuring function arguments #1936

peaceamongworlds opened this issue Jan 10, 2021 · 1 comment · Fixed by #1940

Comments

@peaceamongworlds
Copy link
Contributor

peaceamongworlds commented Jan 10, 2021

It would be nice to have support for destructuring within function arguments. For example,

(defn foo [[x y]]
  (+ x y))

(foo [1 2]) ; => 3

I think this would be relatively easy to add by slightly changing the definition of the defn macro, or maybe a new defn+ macro. A possible implementation could be (this ignores any possible &optional and &rest variables)

(defmacro defn+ [fn-name args &rest body]
  (setv arg-list (lfor _ args (gensym)))
  `(defn ~fn-name
     ~arg-list
     (setv ~args ~arg-list)
     ~@body))

Associative destructuring like in clojure would also be really useful, but I can't see how to make this work nicely with python's list destructuring. As a starting point, this simple example works but is not recursive:

(defmacro destructure-assoc [pattern coll]
  `(setv ~(.values pattern) (lfor k ~(.keys pattern) (.get ~coll k None))))

(destructure-assoc {"as" [a b] "c" c} {"as" [4 5] "c" 6})
[a b c] ; => [4 5 6]
@Kodiologist
Copy link
Member

The sequence version used to be built-in, and then was removed by #1590. A pull request to add something more like Clojure, namely #1328, eventually petered out.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants