user2290820
user2290820

Reputation: 2749

Can we have anonymous function inside defmodules?

Can we do Something like

defmodule EmailMatch do
    match_email = fn(id) -> Regex.run ~r/[a-zA-Z]+\s*\@[a-zA-Z]+\.[a-z]+/, id end
end

and use it like:

EmailMatch.match_email("[email protected]")

albeit above gives:

** (UndefinedFunctionError) undefined function EmailMatch.match_email/1
    EmailMatch.match_email("[email protected]")

Upvotes: 1

Views: 224

Answers (2)

user2290820
user2290820

Reputation: 2749

Actually I found this to be just a syntactic sugar and easier to do. Anonymous functions binding and calling by another variable isn't really something I've found in the docs.

defmodule EmailMatch do
  @moduledocs """
   matching email
  """
  def match_email(id), do:Regex.run ~r/[a-zA-Z]+\s*\@[a-zA-Z]+\.[a-z]+/, id

end

I think I'll have to do with this.

Upvotes: -1

Dogbert
Dogbert

Reputation: 222128

Yes, this code works, but you won't be able to access the function from outside the module or even from the defs inside the module. I guess that's what you mean by "this isn't working" as it compiles fine for me. You can call it from other expressions directly inside the defmodule:

defmodule EmailMatch do
  match_email = fn(id) -> Regex.run ~r/[a-zA-Z]+\s*\@[a-zA-Z]+\.[a-z]+/, id end
  IO.inspect match_email.("[email protected]")
end

Output:

["[email protected]"]

If you want this function to be only available inside other defs in the module, you can use defp to define a private function.

Upvotes: 4

Related Questions