Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir type spec for a function with default parameters

Tags:

elixir

How do I write a type spec for the function that accepts, let's say, one parameter which has a default value? Something like the following:

def foo(bar \\ 10) do
  bar
end

Would it be this:

@spec foo(integer) :: integer

Or what would it be?

Thank you.

like image 377
NoDisplayName Avatar asked May 23 '16 17:05

NoDisplayName


People also ask

What is @spec in Elixir?

For this purpose Elixir has @spec annotation to describe the specification of a function that will be checked by compiler. However in some cases specification is going to be quite big and complicated. If you would like to reduce complexity, you want to introduce a custom type definition.

What is a TypeSpec?

TypeSpec provides metadata describing an object accepted or returned by TensorFlow APIs. Concrete subclasses, such as tf. TensorSpec and tf. RaggedTensorSpec , are used to describe different value types.


2 Answers

Yes.

I would add that if your question is if there is a difference between the typespec of a function which has an argument with a default value and an argument that doesn't, then no there is no difference.

like image 156
Joey Feldberg Avatar answered Sep 19 '22 22:09

Joey Feldberg


It works as expected because you actually define two functions.

@spec foo(integer) :: integer
def foo(bar \\ 10) do
  bar
end

Is equivalent to:

def foo() do
  foo(10)
end

@spec foo(integer) :: integer
def foo(bar) do
  bar
end

So you basically end up with two functions but only one of them has @spec.

like image 26
Michał Szajbe Avatar answered Sep 19 '22 22:09

Michał Szajbe