papasmurf22
Find the first recurring character in a string
hi everyone,
I have the simple problem of “Find the first recurring character in a string” that I can easily think about solving in an OO language with a for loop and a counter variable but am wondering how you would solve this “the functional way”.
i.e: If “ABCDAHWX” was passed in to the function as argument you would return the first recurring character “A”.
What is the FP way to do this in elixir? Would u use recursion or maybe matching on function parameters?
Thank you for your time
Most Liked
LostKobrakai
I’d use Enum.reduce_while:
result = Enum.reduce_while(String.graphemes("ABCDAHWX"), [], fn character, prev ->
if character in prev, do: {:halt, character}, else: {:cont, [character | prev]}
end)
with char when is_binary(char) <- result do
char
else
[_ | _] -> :no_duplicates
end
peerreynders
https://www.regular-expressions.info/
https://regexr.com/ set the RegEx Engine to PCRE (Perl Compatible Regular Expressions)
idi527
Of course, I expect the regular expression version to be faster
iex(2)> :timer.tc fn -> Enum.each 1..1_000, fn _ -> Test.first_recurring("ABCDAHWX") end end
{1876, :ok}
iex(4)> reg = ~r/(.).*?\1/
~r/(.).*?\1/
iex(6)> :timer.tc fn -> Enum.each 1..1_000, fn _ -> Regex.run(reg, "ABCDAHWX") end end
{5585, :ok}
iex(7)> :timer.tc fn -> Enum.each 1..1_000, fn _ -> Regex.run(reg, "ABCDAHWX") end end
{3823, :ok}
iex(8)> :timer.tc fn -> Enum.each 1..1_000, fn _ -> Regex.run(reg, "ABCDAHWX") end end
{4058, :ok}
Although the regex pattern is not compiled, but the elixir version (above) is not optimized either. I usually find regexes to be much slower than erlang’s pattern matching since they do much more work.









