The following is my solution to one of the exercises of “Programming Elixir 1.2” and I wondered if it is considered an anitpattern to have two functions (upcase_first_char and downcase_till_point) which call each other - or if it is ok if there are not too many functions which call each other. Other solutions use a parameter (true/false) to know if they have to upcase or downcase a character but I think the code is better readable if I use different method names instead.
The exercise was:
Write a function to capitalize the sentences in a string. Each sentence is terminated by a period and a space. Right now, the case of the characters in the string is random.
iex> capitalize_sentences("oh. a DOG. woof. ")
"Oh. A dog. Woof. "
My solution is:
defmodule MyStrings do
def capitalize_sentences(string), do: upcase_first_char(string)
defp upcase_first_char(<< " ", tail :: binary >>), do: " " <> upcase_first_char(tail)
defp upcase_first_char(<< head :: utf8, tail :: binary >>), do: String.upcase(<<head>>) <> downcase_till_point(tail)
defp upcase_first_char(<<>>), do: ""
defp downcase_till_point(<< ".", tail :: binary >>), do: "." <> upcase_first_char(tail)
defp downcase_till_point(<< head :: utf8, tail :: binary >>), do: String.downcase(<<head>>) <> downcase_till_point(tail)
defp downcase_till_point(<<>>), do: ""
end
I know that it’s easier to do it using String.split und Enum.join but I wanted to get familiar with binary pattern matching.
Ok or not ok?
Regards
Meinert