Hi all
I have following code snippet and do not know what -> sign means here:
segment, acc -> quote do: (unquote(acc) <> unquote(segment))
and the whole function code snippet:
defp interpolate(string) do
~r/(?<head>)%{[^}]+}(?<tail>)/
|> Regex.split(string, on: [:head, :tail])
|> Enum.reduce "", fn <<"%{" <> rest>>, acc ->
key = String.to_atom(String.rstrip(rest, ?}))
quote do
unquote(acc) <> to_string(Dict.fetch!(bindings, unquote(key)))
end
segment, acc -> quote do: (unquote(acc) <> unquote(segment))
end
end
Thanks for help
The ->
sign is part of an anonymous function here. It’s used to separate the function definition from the function body.
fn(arg1, arg2) ->
body
end
The parentheses are optional and were left out in your example.
fn <<"%{" <> rest>>, acc ->
# function body...
end
More generally, the ->
sign is used to separate a “pattern” from code that should execute if that pattern matches. For example, in case
statements:
case value do
"foo" -> IO.puts("It's foo")
"bar" -> IO.puts("It's bar")
_ -> IO.puts("unknown")
end
Since anonymous functions actually support multiple definition and pattern matching, the ->
sign is performing the same purpose there.
fn
("hello", suffix) -> IO.puts("Hello, #{suffix}!")
("goodbye", name) -> IO.puts("Sorry to see you go, #{name}!")
end
9 Likes
It might help to look at the function with slightly different formatting. I tend break the line and put multiple anonymous function clauses at the same indent level so that it is easier for me to identify the different functions and their bodies.
defp interpolate(string) do
~r/(?<head>)%{[^}]+}(?<tail>)/
|> Regex.split(string, on: [:head, :tail])
|> Enum.reduce "", fn
<<"%{" <> rest>>, acc ->
key = String.to_atom(String.rstrip(rest, ?}))
quote do
unquote(acc) <> to_string(Dict.fetch!(bindings, unquote(key)))
end
segment, acc -> quote do: (unquote(acc) <> unquote(segment))
end
end
1 Like