Created
September 1, 2014 22:27
-
-
Save dgoldie/f052ce147541f9a7ee52 to your computer and use it in GitHub Desktop.
Experiments with Elixir strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Exp do | |
def cat_consonants(list), do: cat_consonants(list, []) | |
def cat_consonants([one, two | tail], acc) do | |
combo = one <> two | |
case has_vowel?(combo) do | |
true -> | |
new_head = [two | tail] | |
new_tail = [one | acc] | |
false -> | |
new_head = [combo | tail] | |
new_tail = acc | |
end | |
cat_consonants(new_head, new_tail) | |
end | |
def cat_consonants([only_one_left], acc) do | |
Enum.reverse([only_one_left | acc]) | |
end | |
def cat_consonants([], acc), do: Enum.reverse(acc) | |
defp has_vowel?(character) do | |
String.match?(character, ~r/[aeiou]/) | |
end | |
end | |
defmodule ExperimentsTest do | |
use ExUnit.Case | |
test "special string split with odd no. of characters" do | |
str = "caterpillar" | |
result = str | |
|> String.split("") | |
|> Exp.cat_consonants | |
assert result == [ "c", "a", "t", "e", "rp", "i", "ll", "a", "r"] | |
end | |
test "special string split with even no. of characters" do | |
str = "caterpillars" | |
result = str | |
|> String.split("") | |
|> Exp.cat_consonants | |
assert result == [ "c", "a", "t", "e", "rp", "i", "ll", "a", "rs"] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment