Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is_module guard clause in elixir

Tags:

elixir

I'm passing module to the function and want to use guard clauses (function is designed to have :atom or module) passed to it.

How can I check that argument in the function is module (like is_atom for atoms?)

like image 886
asiniy Avatar asked Oct 25 '25 00:10

asiniy


2 Answers

This is not possible with just guard clauses. I would use Code.ensure_loaded?/1 in the function body for this. In addition to returning true/false if the module exists or not, this will also try to load the module if it can find the corresponding beam file in the code path:

iex(1)> defmodule A do
...(1)> end
iex(2)> Code.ensure_loaded?(A)
true
iex(3)> Code.ensure_loaded?(B)
false
iex(4)> Code.ensure_loaded?(Map)
true
iex(5)> Code.ensure_loaded?(:maps)
true
# I created `a.beam` using `erlc` in the same folder as `iex` was started
iex(6)> Code.ensure_loaded?(:a) 
true
like image 76
Dogbert Avatar answered Oct 27 '25 00:10

Dogbert


A module name IS an atom, so other than checking for is_atom, what you're requesting is impossible.

like image 24
pmarreck Avatar answered Oct 26 '25 23:10

pmarreck