Skip to content

Instantly share code, notes, and snippets.

@kan
Last active September 30, 2016 07:57
Show Gist options
  • Save kan/9e8c1a3a1fda95e2f3c35061de76a5de to your computer and use it in GitHub Desktop.
Save kan/9e8c1a3a1fda95e2f3c35061de76a5de to your computer and use it in GitHub Desktop.
defmodule Erolang do
def do_run(code, vars) do
case code do
["set", key, val] ->
{v, vars} = do_run(val, vars)
{nil, Map.put(vars, key, v)}
["get", key] ->
{vars[key], vars}
["+", val1, val2] ->
{v1, vars} = do_run(val1, vars)
{v2, vars} = do_run(val2, vars)
{v1 + v2, vars}
["=", val1, val2] ->
{v1, vars} = do_run(val1, vars)
{v2, vars} = do_run(val2, vars)
{v1 == v2, vars}
["until", cnd, list] ->
case do_run(cnd, vars) do
{false, vars} ->
{_, vars} = do_run(list, vars)
do_run(["until", cnd, list], vars)
{_, vars} ->
{nil, vars}
end
["step"] ->
{nil, vars}
["step" | list] ->
[c | tail] = list
{_, vars} = do_run(c, vars)
do_run(["step" | tail], vars)
val -> {val, vars}
end
end
def run(str) do
do_run(Poison.Parser.parse!(str), %{})
end
end
{_, vars} = Erolang.run("""
["step",
["set", "i", 10],
["set", "sum", 0],
["until", ["=", ["get", "i"], 0], [
"step",
["set", "sum", ["+", ["get", "sum"], ["get", "i"]]],
["set", "i", ["+", ["get", "i"], -1]]
]],
["get", "sum"]
]
""")
IO.inspect(vars)
defmodule Erolang do
def start_link do
Agent.start_link(fn -> %{} end)
end
def get(agent, key) do
Agent.get(agent, fn map -> map[key] end)
end
def get_all(agent) do
Agent.get(agent, fn map -> map end)
end
def put(agent, key, value) do
Agent.update(agent, fn map -> Map.put(map, key, value) end)
end
def do_run(code, agent) do
case code do
["set", key, val] -> put(agent, key, do_run(val, agent))
["get", key] -> get(agent, key)
["+", val1, val2] -> do_run(val1, agent) + do_run(val2, agent)
["=", val1, val2] -> do_run(val1, agent) == do_run(val2, agent)
["until", cnd, list] ->
unless do_run(cnd, agent) do
do_run(list, agent)
do_run(["until", cnd, list], agent)
end
["step"] -> nil
["step" | list] ->
[c | tail] = list
do_run(c, agent)
do_run(["step" | tail], agent)
val -> val
end
end
def run(str, agent) do
do_run(Poison.Parser.parse!(str), agent)
end
end
{:ok, agent} = Erolang.start_link
Erolang.run("""
["step",
["set", "i", 10],
["set", "sum", 0],
["until", ["=", ["get", "i"], 0], [
"step",
["set", "sum", ["+", ["get", "sum"], ["get", "i"]]],
["set", "i", ["+", ["get", "i"], -1]]
]],
["get", "sum"]
]
""", agent)
agent
|> Erolang.get_all
|> IO.inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment