Function for swap casing

42 views
Skip to first unread message

Константин Трегубов

unread,
Aug 1, 2016, 11:21:41 PM8/1/16
to elixir-lang-talk
I read how works functions upcase and downcase and try to think how to realize function swapcase.

in elixir/lib/elixir/unicode/unicode.ex  line308

  # Swapcase

  def swapcase(string), do: swapcase(string, "")

  for {codepoint, upper, lower, _title} <- codes do
    cond do
      lower && codepoint != lower ->
        defp swapcase(unquote(codepoint) <> rest, acc) do
          swapcase(rest, acc <> unquote(lower))
        end
      upper && codepoint != upper ->
        defp swapcase(unquote(codepoint) <> rest, acc) do
          swapcase(rest, acc <> unquote(upper))
        end
      true -> nil
    end
  end

  defp swapcase(<<char, rest::binary>>, acc) do
    swapcase(rest, <<acc::binary, char>>)
  end

  defp swapcase("", acc), do: acc

Result:

iex(17)> r(String.Casing)                                      
warning: redefining module String.Unicode (current version defined in memory)
  unicode.ex:1

warning: redefining module String.Casing (current version defined in memory)
  unicode.ex:294

warning: redefining module String.Break (current version defined in memory)
  unicode.ex:379

warning: redefining module String.Normalizer (current version defined in memory)
  unicode.ex:489

{:reloaded, String.Casing,
 [String.Unicode, String.Casing, String.Break, String.Normalizer]}
iex(18)> String.Casing.swapcase("ПриВЕ!!ббю..WEr5%oe902kj elk")
"пРИве!!ББЮ..weR5%OE902KJ ELK"
iex(19)> 


 If this code fine, can i do PR?))
In ruby this function names "swapcase". In elixir we may use different name like "reversecase", "togglecase".

Ben Wilson

unread,
Aug 2, 2016, 7:49:44 AM8/2/16
to elixir-lang-talk
Please don't post the exact same thing on both the elixir forum and this mailing list. Split discussions are very hard to follow.
Reply all
Reply to author
Forward
0 new messages