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 using 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
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.
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
.