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
First Post!
idi527
Same way, probably.
defmodule Test do
def first_recurring(str) do
do_first_recurring(str, [])
end
defp do_first_recurring(<<letter, rest::bytes>>, chars) do
if letter in chars do
<<letter>>
else
do_first_recurring(rest, [letter | chars])
end
end
defp do_first_recurring("", _chars), do: nil
end
Not particularly efficient, but should provide you with a general idea.
iex(2)> Test.first_recurring("ABCDAHWX")
"A"
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.
Last Post!
Qqwy
Trending in Questions
Other Trending Topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #elixirconf-us
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









