Created
February 18, 2014 02:43
-
-
Save d0rc/9063706 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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