Skip to content

Commit 01a0f34

Browse files
authored
Merge pull request #127 from phel-lang/docs/multi-arity-func-args
Multi-arity function arguments
2 parents b6a07bb + a24bf52 commit 01a0f34

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

content/documentation/functions-and-recursion.md

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,11 +7,18 @@ weight = 7
77

88
```phel
99
(fn [params*] expr*)
10+
11+
(fn
12+
([params1*] expr1*)
13+
([params2*] expr2*)
14+
...)
1015
```
1116

1217
Defines a function. A function consists of a list of parameters and a list of expression. The value of the last expression is returned as the result of the function. All other expression are only evaluated for side effects. If no expression is given, the function returns `nil`.
1318

14-
Function also introduce a new lexical scope that is not accessible outside the function.
19+
Functions can define multiple arities. When calling such a function, the clause matching the number of provided arguments is chosen. Variadic clauses are supported for at most one arity and must be the one with the most parameters. If no arity matches, a readable compile-time or runtime error is thrown.
20+
21+
Function also introduces a new lexical scope that is not accessible outside the function.
1522

1623
```phel
1724
(fn []) # Function with no arguments that returns nil
@@ -24,7 +31,13 @@ Function can also be defined as variadic function with an infinite amount of arg
2431

2532
```phel
2633
(fn [& args] (count args)) # A variadic function that counts the arguments
34+
2735
(fn [a b c &]) # A variadic function with extra arguments ignored
36+
37+
(fn # A multi-arity function
38+
([] "hi")
39+
([name] (str "hi " name))
40+
([greeting name & rest] (str greeting " " name rest)))
2841
```
2942

3043
There is a shorter form to define an anonymous function. This omits the parameter list and names parameters based on their position.
@@ -44,13 +57,23 @@ There is a shorter form to define an anonymous function. This omits the paramete
4457

4558
```phel
4659
(defn name docstring? attributes? [params*] expr*)
60+
61+
(defn name docstring? attributes?
62+
([params1*] expr1*)
63+
([params2*] expr2*)
64+
...)
4765
```
4866

49-
Global functions can be defined using `defn`.
67+
Global functions can be defined using `defn`. Like anonymous functions, they may provide multiple arities. The most specific clause based on the number of arguments is chosen at call time. A single variadic clause is allowed and must declare the maximum number of arguments.
5068

5169
```phel
5270
(defn my-add-function [a b]
5371
(+ a b))
72+
73+
(defn greet
74+
([] "hi")
75+
([name] (str "hi " name))
76+
([greeting name] (str greeting " " name)))
5477
```
5578

5679
Each global function can take an optional doc comment and attribute map.

0 commit comments

Comments
 (0)