Skip to content

Instantly share code, notes, and snippets.

@nurugger07
Created March 27, 2018 17:03
Show Gist options
  • Save nurugger07/ec67e69dc4d1aed245e79546c2f77c5b to your computer and use it in GitHub Desktop.
Save nurugger07/ec67e69dc4d1aed245e79546c2f77c5b to your computer and use it in GitHub Desktop.
Maybe apply a function to a module
defmodule Maybe do
def apply(mod, fun, args) when is_list(args) do
with true <- function_exported?(mod, fun, Enum.count(args)) do
Kernel.apply(mod, fun, args)
else
false ->
"No function exported for #{mod}"
end
end
def apply(mod, fun, args),
do: Maybe.apply(mod, fun, [args])
end
defmodule ModuleA do
def say(phrase),
do: IO.inspect(phrase, label: "ModuleA says: ")
end
defmodule ModuleB do
def say(phrase),
do: IO.inspect(phrase, label: "ModuleB says: ")
end
defmodule ModuleC do
end
[ModuleA, ModuleB, ModuleC] |> Enum.map(&(Maybe.apply(&1, :say, ["hello"]))) |> IO.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment