I think there are more understandable approaches to this that might work for you. Using regex:
Regex.scan(~r/a/, str) |> Enum.count
or dividing the string into Unicode characters, and then counting on it:
str |> String.graphemes |> Enum.count(fn(c) -> c == "a" end)
These are not very efficient approaches, but the performance impact should be negligible with a (relatively small!) Line, which is only 500 characters long.
, , . , .
defmodule Recursive do
def count(str, <<c::utf8>>) do
do_count(str, c, 0)
end
defp do_count(<<>>, _, acc) do
acc
end
defp do_count(<<c::utf8, rest::binary>>, c, acc) do
do_count(rest, c, acc + 1)
end
defp do_count(<<_::utf8, rest::binary>>, c, acc) do
do_count(rest, c, acc)
end
end
, , benchfella . " " @DeboraMartins, . .
split length 500000 5.90 µs/op
recursive 100000 10.63 µs/op
regex count 100000 24.35 µs/op
graphemes count 10000 118.29 µs/op
split length 100 11150.59 µs/op
recursive 100 12002.20 µs/op
regex count 100 25313.40 µs/op
graphemes count 10 218846.20 µs/op