Croma.Defun
Module that provides Croma.Defun.defun/2
macro.
Summary↑
defun(arg1, list2) | Defines a function together with its typespec. This provides a lighter-weight syntax for functions with type specifications and functions with multiple clauses |
defunp(arg1, list2) | Defines a private function together with its typespec.
See |
defunpt(arg1, list2) | Defines a unit-testable private function together with its typespec.
See |
Macros
Defines a function together with its typespec. This provides a lighter-weight syntax for functions with type specifications and functions with multiple clauses.
Example
The following examples assume that Croma.Defun
is imported
(you can import it by use Croma
).
defun f(a: integer, b: String.t) :: String.t do
"#{a} #{b}"
end
The code above is expanded to the following function definition.
@spec f(integer, String.t) :: String.t
def f(a, b) do
"#{a} #{b}"
end
Function with multiple clauses and/or pattern matching on parameters can be defined
in the same way as case do ... end
:
defun dumbmap(as: [a], f: (a -> b)) :: [b] when a: term, b: term do
([] , _) -> []
([h | t], f) -> [f.(h) | dumbmap(t, f)]
end
is converted to
@spec dumbmap([a], (a -> b)) :: [b] when a: term, b: term
def dumbmap(as, f)
def dumbmap([], _) do
[]
end
def dumbmap([h | t], f) do
[f.(h) | dumbmap(t, f)]
end
Generating guards from argument types
Simple guard expressions can be generated by defun/2
using g[type]
syntax.
For example,
defun f(s: g[String.t], i: g[integer]) :: String.t do
"#{s} #{i}"
end
is converted to the following function with when is_integer(i)
guard.
@spec f(String.t, integer) :: String.t
def f(s, i)
def f(s, i) when is_binary(s) and is_integer(i) do
"#{s} #{i}"
end
For supported types of guard-generation please refer to the source code of Croma.Guard.make/3
.
Known limitations
- Pattern matching against function parameters should use
(param1, param2) when guards -> block
style. In other words, pattern matching in the form ofdefun f({:ok, _})
is not supported. - Overloaded typespecs are not supported.
- Guard generations are not allowed to be used with clauses.
Defines a private function together with its typespec.
See defun/2
for usage of this macro.
Defines a unit-testable private function together with its typespec.
See defun/2
for usage of this macro.
See also Croma.Defpt.defpt/2
.