Skip to content

Commit

Permalink
Merge pull request #793 from kirbyfan64/destruct-args
Browse files Browse the repository at this point in the history
Add argument destructuring
  • Loading branch information
berkerpeksag committed Apr 30, 2015
2 parents d11014d + 4ead84b commit 5f1776f
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
13 changes: 13 additions & 0 deletions hy/compiler.py
Original file line number Diff line number Diff line change
Expand Up @@ -1948,6 +1948,19 @@ def compile_function_def(self, expression):
raise HyTypeError(expression,
"First argument to (fn) must be a list")
ret, args, defaults, stararg, kwargs = self._parse_lambda_list(arglist)
for i, arg in enumerate(args):
if isinstance(arg, HyList):
# Destructuring argument
if not arg:
raise HyTypeError(arglist,
"Cannot destruct empty list")
args[i] = var = HySymbol(self.get_anon_var())
expression = HyExpression([
HyExpression([
HyString("setv"), arg, var
])]
) + expression
expression = expression.replace(arg[0])

if PY34:
# Python 3.4+ requires that args are an ast.arg object, rather
Expand Down
6 changes: 6 additions & 0 deletions tests/compilers/test_ast.py
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,12 @@ def test_ast_tuple():
assert type(code) == ast.Tuple


def test_argument_destructuring():
""" Ensure argument destructuring compilers. """
can_compile("(fn [[a b]] (print a b))")
cant_compile("(fn [[]] 0)")


def test_lambda_list_keywords_rest():
""" Ensure we can compile functions with lambda list keywords."""
can_compile("(fn (x &rest xs) (print xs))")
Expand Down
5 changes: 5 additions & 0 deletions tests/native_tests/language.hy
Original file line number Diff line number Diff line change
Expand Up @@ -1153,3 +1153,8 @@
(assert
(= (identify-keywords 1 "bloo" :foo)
["other" "other" "keyword"])))

(defn test-argument-destr []
"Make sure argument destructuring works"
(defn f [[a b] [c]] (, a b c))
(assert (= (f [1 2] [3]) (, 1 2 3))))

0 comments on commit 5f1776f

Please sign in to comment.