Skip to content

Instantly share code, notes, and snippets.

@d0rc
Created February 18, 2014 02:43
Show Gist options
  • Select an option

  • Save d0rc/9063706 to your computer and use it in GitHub Desktop.

Select an option

Save d0rc/9063706 to your computer and use it in GitHub Desktop.
defmodule Parser do
@dict HashDict.new([{"foo", "bar"}, {"baz", "buzz"}])
defrecord :state, [in_match: false, escaping: false, key: ""]
def translate(string) do
translate(string, :state[])
end
defp translate("", _), do: ""
defp translate(<<"\\", rest:: binary>>, state) do
<<"\\", translate(rest, state.escaping(true))::binary>>
end
defp translate(<<char::[binary, size(1)], rest::binary>>, state = :state[escaping: true]) do
<<char::binary, translate(rest, state.escaping(false))::binary>>
end
defp translate(<<"$", rest::binary>>, state = :state[in_match: true]) do
case @dict[state.key] do
nil -> raise SyntaxError
word -> <<word::binary, translate(rest, state.in_match(false))::binary>>
end
end
defp translate(<<"$", rest::binary>>, state = :state[in_match: false]) do
translate(rest, state.in_match(true).key(""))
end
defp translate(<<char::[binary, size(1)], rest::binary>>, state = :state[in_match: true]) do
translate(rest, state.key("#{state.key}#{char}"))
end
defp translate(<<char::[binary, size(1)], rest::binary>>, state) do
<<char::binary, translate(rest, state)::binary>>
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment