What is a term?

I have been studying how to save files to the filesystem and I had some doubts related to the Erlang functions responsible to deal with binaries.

For instance:

def saveFile(path, file) do 
  binary = :erlang.term_to_binary(file) 
end  

def loadFile(path) do 
 {status, binary} = File.read(path) 

 case status do 
  :ok -> :erlang.binary_to_term(binary) 
  :error -> "File not exists. Did you write the correct path?"
end 

What is the “term” word used in the erlang functions above?

1 Like

Term is any Erlang term. In other words, any value in Erlang is a term.

1 Like

So any value can be converted to a binary?

Yes, but beware that it will use External Term Format, not “human readable format”.

EDIT: Not only it can be encoded into binary, it have to. Otherwise the Distributed Erlang couldn’t exist at all.

5 Likes

Alrighttt, now i understand it. Thanks!!

1 Like

yes, and they’re not kidding when they mean “any term”. For example, do this:

f = fn x -> x + 1 end

then save the term in f to a file. Close your elixir session, start a new one, open the file into a variable f in your new session and then do this:

f.(4)
7 Likes