empty function declaration?

1,493 views
Skip to first unread message

Alex Shneyderman

unread,
Jul 29, 2014, 5:42:07 PM7/29/14
to elixir-l...@googlegroups.com
I see this pattern quite often:

  @spec send_resp(t) :: t | no_return
  def send_resp(conn)

  def send_resp(%Conn{state: :unset}) do
    raise ArgumentError, message: "cannot send a response that was not set"
  end
 
 ...

  def send_resp(%Conn{}) do
    raise AlreadySentError
  end


pattern being the first definition of the function that has no body.

What does this mean? And why does this work?

Thanks & cheers,
Alex.

Eric Meadows-Jönsson

unread,
Jul 29, 2014, 5:47:09 PM7/29/14
to elixir-l...@googlegroups.com
It's called a function head, we use it to document the function and to define default arguments.

ExDoc will use the argument names from the function head in the generated docs, so it is way to give good names to the arguments even if you have clauses with pattern matches. It is also the only place you can define default arguments for functions with multiple clauses.


--
You received this message because you are subscribed to the Google Groups "elixir-lang-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-ta...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Eric Meadows-Jönsson

Alexei Sholik

unread,
Jul 29, 2014, 5:48:56 PM7/29/14
to elixir-l...@googlegroups.com


--
You received this message because you are subscribed to the Google Groups "elixir-lang-talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-ta...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.



--
Best regards
Alexei Sholik

Alex Shneyderman

unread,
Jul 29, 2014, 6:02:34 PM7/29/14
to elixir-l...@googlegroups.com
still, seems a bit odd of a construct. so, there are basically two case for the use:

1. to document, which IMO is a weak case since you can easily do that with the spec

@spec send_resp(conn :: t) :: t | no_return

and doing it with the spec is probably more logical since well specs are for documenting.

2. define default values. this seems like a valid case although probably not very common 
one. 

Anyway, thanks for the explanations and pointers.

Cheers,
Alex.

Paul Schoenfelder

unread,
Jul 30, 2014, 11:13:47 AM7/30/14
to elixir-l...@googlegroups.com
Honestly I hit #2 pretty regularly. Once I started heavily using pattern matching and recursive function calls, the odds of having a multi-clause function with default values is pretty high.

Paul
Reply all
Reply to author
Forward
0 new messages