dubesoftware
Hi all,
I’m learning Elixir/OTP and am stumped by a certain behaviour. I’m declaring an anonymous function in a module, then when I attempt to call that function from another module, I get an UndefinedFunctionError error. I can alias the anonymous function’s module, but cannot even import the function using the syntax import Module, only: [anon_func]. Please see the code below. What gives?
Module that defines anonymous function:
defmodule Servy.PowerNapper do power_nap = fn -> time = :rand.uniform(10_000) :timer.sleep(time) time end end
and the caller module
`
defmodule Servy.PowerNapperClient do
alias Servy.PowerNapper
parent = self()
spawn(fn → send(parent, {:slept, PowerNapper.power_nap.()}) end)
receive do
{:slept, time} → IO.puts “Slept #{time} ms”
end
end
`
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #blog-post
- #phoenix_html
- #iex
- #graphql
- #ai
- #genstage
- #elixirconf-us
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex











Showing Posts 1 to 4- Show Best Posts
- Show All Posts (oldest first)
- Show All Posts (newest first)
al2o3cr
Nope, that’s not what that does.
power_napis a local variable inside of thedoblock but it doesn’t stick around after the module is compiled and it isn’t visible outside.Also, an linguistic nitpick: an “anonymous function” would be a function without a name - but the intent of the code you posted is to name the function
PowerNapper.power_nap!What specifically were you hoping to get with this approach, compared to doing a standard
def power_nap doinServy.PowerNapper?Related:
self()here will be the Elixir compiler! Thereceivewill happen whilePowerNapperClientis being compiled.dubesoftware
Thanks, this clicked! It wasn’t a function definition.
Yep, I did think about this! An anon function would not be named. That is indeed a misnomer.
This is sample code from the course I’m taking. Please see the attached screen shot. However, separating the calling code into its own module was my idea.
cjbottaro
My guy… triple backticks…
The only things “exported” out of a module are public functions, i.e. anything defined by
def.* Public types too
** Public submodules also
*** Now I’m questioning all of reality… what else??
dubesoftware