Skip to content

Instantly share code, notes, and snippets.

@danj3
Created March 15, 2018 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danj3/141d3a63ab78a4420dc5658333685437 to your computer and use it in GitHub Desktop.
Save danj3/141d3a63ab78a4420dc5658333685437 to your computer and use it in GitHub Desktop.
Elixir: example of turning a term to a string and a string to a term
defmodule TermRoundTrip do
@moduledoc """
Convert a term to a readable string then back to a term
"""
def term_to_binary( term ) do
:io_lib.format("~p.~n", [ term ] )
|> :erlang.iolist_to_binary
end
def binary_to_term( binary ) do
{ :ok, t, _p } =
binary
|> String.to_charlist
|> :erl_scan.string
:erl_parse.parse_term( t )
end
def main do
term = [ %{ a: 7, b: 12 }, 55, "and" ]
str = term_to_binary( term )
{ :ok, term2 } = binary_to_term( str )
IO.puts( str )
IO.inspect( term )
IO.inspect( term2 )
IO.inspect( term === term2 )
end
end
TermRoundTrip.main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment