Created
March 27, 2018 17:03
-
-
Save nurugger07/ec67e69dc4d1aed245e79546c2f77c5b to your computer and use it in GitHub Desktop.
Maybe apply a function to a module
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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