Created
March 15, 2018 00:34
-
-
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
This file contains 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 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