Skip to content

Commit 15ac6e9

Browse files
author
José Valim
committed
Improve docs for function
1 parent 01d5701 commit 15ac6e9

File tree

2 files changed

+45
-7
lines changed

2 files changed

+45
-7
lines changed

lib/elixir/lib/kernel.ex

Lines changed: 44 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -2028,19 +2028,57 @@ defmodule Kernel do
20282028
x -> x * 2
20292029
end)
20302030
2031-
## Function retrieval
2031+
"""
2032+
defmacro function(args)
20322033
2033-
The `function` macro can also be used to retrieve local or remote
2034-
functions:
2034+
@doc """
2035+
Retrieves a local or an imported function.
2036+
2037+
## Examples
20352038
20362039
f = function(:is_atom, 1)
20372040
f.(:foo) #=> true
20382041
2039-
f = function(List, :flatten, 1)
2040-
f.([1,[2],3]) #=> [1,2,3]
2042+
Notice that local functions cannot be retrieved dynamically,
2043+
the following, for example, wouldn't work:
2044+
2045+
some_fun = :is_atom
2046+
function(some_fun, 1)
2047+
2048+
In such cases, one should use `function/3`:
2049+
2050+
some_fun = :is_atom
2051+
function(SomeModule, some_fun, 1)
2052+
2053+
## Shortcut syntax
2054+
2055+
One can use a shortcut syntax to retrieve such functions,
2056+
that resembles Erlang's `fun`:
2057+
2058+
f = function(is_atom/1)
2059+
f.(:foo)
20412060
20422061
"""
2043-
defmacro function(args)
2062+
defmacro function(function, arity)
2063+
2064+
@doc """
2065+
Retrieves a function from a module.
2066+
2067+
## Examples
2068+
2069+
f = function(Kernel, :is_atom, 1)
2070+
f.(:foo) #=> true
2071+
2072+
## Shortcut syntax
2073+
2074+
One can use a shortcut syntax to retrieve such functions,
2075+
that resembles Erlang's `fun`:
2076+
2077+
f = function(Kernel.is_atom/1)
2078+
f.(:foo) #=> true
2079+
2080+
"""
2081+
defmacro function(module, function, arity)
20442082
20452083
@doc """
20462084
Matches the given condition against the match clauses.

lib/elixir/src/elixir_macros.erl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ translate({ function, Meta, [_, _] = Args }, S) ->
7676
Else -> Else
7777
end;
7878
_ ->
79-
syntax_error(Meta, S#elixir_scope.file, "cannot dynamically retrieve local function. use function(module, fun, arity) instead")
79+
syntax_error(Meta, S#elixir_scope.file, "cannot dynamically retrieve local function, use function/3 instead")
8080
end;
8181

8282
translate({ function, Meta, [_,_,_] = Args }, S) when is_list(Args) ->

0 commit comments

Comments
 (0)