From 771a49c2ffc26497086b4667ba687d39a896b4cd Mon Sep 17 00:00:00 2001 From: Juan Soto Date: Mon, 26 Feb 2018 04:31:49 -0500 Subject: [PATCH] Run `mix format` (#391) Closes #387. --- .formatter.exs | 3 + exercises/accumulate/accumulate_test.exs | 16 +- exercises/acronym/acronym_test.exs | 4 +- exercises/acronym/example.exs | 7 +- .../all-your-base/all-your-base-test.exs | 4 +- exercises/all-your-base/example.exs | 21 +- exercises/allergies/allergies.exs | 6 +- exercises/allergies/allergies_test.exs | 28 +- exercises/anagram/anagram.exs | 3 +- exercises/anagram/anagram_test.exs | 26 +- exercises/anagram/example.exs | 3 +- exercises/atbash-cipher/atbash_cipher.exs | 4 +- .../atbash-cipher/atbash_cipher_test.exs | 4 +- exercises/bank-account/bank_account_test.exs | 15 +- exercises/beer-song/beer_song.exs | 4 +- exercises/beer-song/beer_song_test.exs | 450 +++++++++--------- exercises/beer-song/example.exs | 8 +- .../binary_search_tree_test.exs | 4 +- exercises/binary-search-tree/example.exs | 2 +- exercises/binary-search/binary_search.exs | 1 - .../binary-search/binary_search_test.exs | 4 +- exercises/binary-search/example.exs | 4 +- exercises/binary/binary.exs | 2 +- exercises/binary/binary_test.exs | 4 +- exercises/binary/example.exs | 4 +- exercises/bob/bob.exs | 3 +- exercises/bob/bob_test.exs | 4 +- exercises/bowling/bowling.exs | 5 +- exercises/bowling/bowling_test.exs | 329 +++---------- exercises/bowling/example.exs | 34 +- exercises/bracket-push/bracket_push.exs | 3 +- exercises/bracket-push/bracket_push_test.exs | 8 +- exercises/bracket-push/example.exs | 11 +- exercises/change/change.exs | 3 +- exercises/change/change_test.exs | 4 +- exercises/change/example.exs | 6 +- exercises/clock/clock_test.exs | 16 +- exercises/clock/example.exs | 8 +- .../collatz-conjecture/collatz_conjecture.exs | 1 - .../collatz_conjecture_test.exs | 6 +- exercises/collatz-conjecture/example.exs | 2 +- exercises/connect/connect.exs | 3 +- exercises/connect/connect_test.exs | 70 +-- exercises/connect/example.exs | 22 +- exercises/crypto-square/crypto_square.exs | 3 +- .../crypto-square/crypto_square_test.exs | 4 +- exercises/crypto-square/example.exs | 11 +- exercises/custom-set/custom_set.exs | 2 +- exercises/custom-set/custom_set_test.exs | 4 +- exercises/custom-set/example.exs | 9 +- exercises/diamond/diamond.exs | 3 +- exercises/diamond/diamond_test.exs | 38 +- exercises/diamond/example.exs | 20 +- .../difference_of_squares.exs | 6 +- .../difference_of_squares_test.exs | 11 +- exercises/difference-of-squares/example.exs | 7 +- exercises/diffie-hellman/diffie_hellman.exs | 10 +- .../diffie-hellman/diffie_hellman_test.exs | 66 ++- exercises/diffie-hellman/example.exs | 16 +- exercises/dominoes/dominoes.exs | 1 - exercises/dominoes/dominoes_test.exs | 22 +- exercises/dominoes/example.exs | 14 +- exercises/dot-dsl/dot.exs | 1 - exercises/dot-dsl/dot_dsl_test.exs | 165 ++++--- exercises/dot-dsl/example.exs | 28 +- exercises/etl/etl.exs | 1 - exercises/etl/etl_test.exs | 47 +- exercises/etl/example.exs | 12 +- exercises/flatten-array/flatten_array.exs | 1 - .../flatten-array/flatten_array_test.exs | 16 +- exercises/forth/example.exs | 10 +- exercises/forth/forth.exs | 15 +- exercises/forth/forth_test.exs | 171 ++++--- exercises/gigasecond/example.exs | 2 +- exercises/gigasecond/gigasecond.exs | 4 +- exercises/gigasecond/gigasecond_test.exs | 4 +- exercises/grade-school/example.exs | 6 +- exercises/grade-school/grade_school_test.exs | 48 +- exercises/grade-school/school.exs | 9 +- exercises/grains/example.exs | 13 +- exercises/grains/grains.exs | 2 - exercises/grains/grains_test.exs | 30 +- exercises/grep/example.exs | 40 +- exercises/grep/grep.exs | 3 +- exercises/grep/grep_test.exs | 220 +++++---- exercises/hamming/example.exs | 5 +- exercises/hamming/hamming_test.exs | 11 +- exercises/hello-world/example.exs | 2 +- exercises/hello-world/hello_world.exs | 2 +- exercises/hello-world/hello_world_test.exs | 4 +- exercises/hexadecimal/example.exs | 15 +- exercises/hexadecimal/hexadecimal.exs | 1 - exercises/hexadecimal/hexadecimal_test.exs | 6 +- exercises/isbn-verifier/example.exs | 2 +- exercises/isbn-verifier/isbn_verifier.exs | 3 +- .../isbn-verifier/isbn_verifier_test.exs | 4 +- exercises/isogram/example.exs | 10 +- exercises/isogram/isogram.exs | 4 +- exercises/isogram/isogram_test.exs | 5 +- exercises/kindergarten-garden/example.exs | 18 +- exercises/kindergarten-garden/garden_test.exs | 21 +- exercises/largest-series-product/example.exs | 19 +- .../largest_series_product.exs | 4 +- .../largest_series_product_test.exs | 10 +- exercises/leap/example.exs | 4 +- exercises/leap/leap.exs | 1 - exercises/leap/leap_test.exs | 4 +- exercises/list-ops/example.exs | 19 +- exercises/list-ops/list_ops.exs | 9 +- exercises/list-ops/list_ops_test.exs | 47 +- exercises/luhn/example.exs | 33 +- exercises/luhn/luhn.exs | 2 - exercises/luhn/luhn_test.exs | 4 +- exercises/markdown/example.exs | 54 ++- exercises/markdown/markdown.exs | 12 +- exercises/markdown/markdown_test.exs | 9 +- exercises/matrix/example.exs | 12 +- exercises/matrix/matrix.exs | 1 - exercises/matrix/matrix_test.exs | 22 +- exercises/meetup/example.exs | 33 +- exercises/meetup/meetup.exs | 12 +- exercises/meetup/meetup_test.exs | 4 +- exercises/minesweeper/minesweeper.exs | 4 +- exercises/minesweeper/minesweeper_test.exs | 28 +- exercises/nth-prime/example.exs | 14 +- exercises/nth-prime/nth_prime.exs | 1 - exercises/nth-prime/nth_prime_test.exs | 6 +- exercises/nucleotide-count/example.exs | 7 +- .../nucleotide-count/nucleotide_count.exs | 3 - .../nucleotide_count_test.exs | 4 +- exercises/ocr-numbers/example.exs | 6 +- exercises/ocr-numbers/ocr_numbers.exs | 3 +- exercises/ocr-numbers/ocr_numbers_test.exs | 124 +++-- exercises/palindrome-products/example.exs | 9 +- .../palindrome_products.exs | 1 - .../palindrome_products_test.exs | 16 +- exercises/pangram/pangram.exs | 2 +- exercises/pangram/pangram_test.exs | 8 +- .../parallel-letter-frequency/example.exs | 12 +- .../parallel-letter-frequency/frequency.exs | 3 +- .../parallel_letter_frequency_test.exs | 7 +- exercises/pascals-triangle/example.exs | 3 +- .../pascals_triangle_test.exs | 34 +- exercises/perfect-numbers/example.exs | 14 +- exercises/perfect-numbers/perfect_numbers.exs | 3 +- .../perfect-numbers/perfect_numbers_test.exs | 35 +- exercises/phone-number/example.exs | 30 +- exercises/phone-number/phone_number.exs | 6 +- exercises/phone-number/phone_number_test.exs | 4 +- exercises/pig-latin/pig_latin.exs | 1 - exercises/pig-latin/pig_latin_test.exs | 6 +- exercises/poker/example.exs | 145 ++++-- exercises/poker/poker.exs | 1 - exercises/poker/poker_test.exs | 12 +- exercises/prime-factors/example.exs | 12 +- exercises/prime-factors/prime_factors.exs | 1 - .../prime-factors/prime_factors_test.exs | 10 +- exercises/protein-translation/example.exs | 26 +- .../protein_translation.exs | 5 +- .../protein_translation_test.exs | 52 +- exercises/pythagorean-triplet/example.exs | 9 +- .../pythagorean_triplet.exs | 5 - .../pythagorean_triplet_test.exs | 6 +- exercises/queen-attack/example.exs | 16 +- exercises/queen-attack/queen_attack.exs | 5 +- exercises/rail-fence-cipher/example.exs | 33 +- .../rail-fence-cipher/rail_fence_cipher.exs | 6 +- .../rail_fence_cipher_test.exs | 4 +- exercises/raindrops/example.exs | 5 +- exercises/raindrops/raindrops.exs | 3 +- exercises/raindrops/raindrops_test.exs | 4 +- exercises/rna-transcription/example.exs | 2 +- .../rna-transcription/rna_transcription.exs | 1 - .../rna_transcription_test.exs | 4 +- exercises/robot-simulator/example.exs | 52 +- exercises/robot-simulator/robot_simulator.exs | 8 +- .../robot-simulator/robot_simulator_test.exs | 51 +- exercises/roman-numerals/example.exs | 27 +- exercises/roman-numerals/roman.exs | 2 +- .../roman-numerals/roman_numerals_test.exs | 4 +- exercises/rotational-cipher/example.exs | 20 +- .../rotational-cipher/rotational_cipher.exs | 1 - .../rotational_cipher_test.exs | 10 +- exercises/run-length-encoding/example.exs | 28 +- exercises/run-length-encoding/rle.exs | 6 +- exercises/run-length-encoding/rle_test.exs | 10 +- exercises/saddle-points/example.exs | 7 +- exercises/saddle-points/saddle_points.exs | 3 - .../saddle-points/saddle_points_test.exs | 4 +- exercises/say/say.exs | 2 +- exercises/say/say_test.exs | 8 +- exercises/scale-generator/example.exs | 29 +- exercises/scale-generator/scale_generator.exs | 4 +- .../scale-generator/scale_generator_test.exs | 33 +- exercises/scrabble-score/scrabble.exs | 3 +- .../scrabble-score/scrabble_score_test.exs | 4 +- exercises/secret-handshake/example.exs | 8 +- .../secret-handshake/secret_handshake.exs | 1 - .../secret_handshake_test.exs | 6 +- exercises/series/example.exs | 4 +- exercises/series/series.exs | 1 - exercises/series/series_test.exs | 7 +- exercises/sieve/example.exs | 9 +- exercises/sieve/sieve.exs | 3 - exercises/sieve/sieve_test.exs | 194 +++++++- exercises/simple-cipher/example.exs | 16 +- exercises/simple-cipher/simple_cipher.exs | 1 - .../simple-cipher/simple_cipher_test.exs | 7 +- exercises/simple-linked-list/example.exs | 4 +- .../simple-linked-list/linked_list_test.exs | 7 +- exercises/space-age/example.exs | 11 +- exercises/space-age/space_age.exs | 12 +- exercises/space-age/space_age_test.exs | 4 +- exercises/spiral-matrix/example.exs | 15 +- exercises/spiral-matrix/spiral.exs | 1 - exercises/spiral-matrix/spiral_test.exs | 42 +- exercises/strain/example.exs | 9 +- exercises/strain/strain.exs | 4 +- exercises/strain/strain_test.exs | 19 +- exercises/sublist/example.exs | 18 +- exercises/sublist/sublist.exs | 1 - exercises/sublist/sublist_test.exs | 34 +- exercises/sum-of-multiples/example.exs | 7 +- .../sum-of-multiples/sum_of_multiples.exs | 1 - .../sum_of_multiples_test.exs | 8 +- exercises/test_helper.exs | 8 +- exercises/tournament/example.exs | 33 +- exercises/tournament/tournament.exs | 1 - exercises/tournament/tournament_test.exs | 67 +-- exercises/transpose/example.exs | 8 +- exercises/transpose/transpose.exs | 2 +- exercises/transpose/transpose_test.exs | 245 ++++------ exercises/triangle/example.exs | 14 +- exercises/triangle/triangle.exs | 3 +- exercises/triangle/triangle_test.exs | 34 +- exercises/twelve-days/example.exs | 16 +- exercises/twelve-days/twelve_days.exs | 3 +- exercises/twelve-days/twelve_days_test.exs | 100 ++-- exercises/word-count/example.exs | 10 +- exercises/word-count/word_count.exs | 3 +- exercises/word-count/word_count_test.exs | 10 +- exercises/wordy/example.exs | 27 +- exercises/wordy/wordy.exs | 5 +- exercises/wordy/wordy_test.exs | 4 +- exercises/zipper/example.exs | 85 ++-- exercises/zipper/zipper.exs | 34 +- exercises/zipper/zipper_test.exs | 39 +- 247 files changed, 2619 insertions(+), 2355 deletions(-) create mode 100644 .formatter.exs diff --git a/.formatter.exs b/.formatter.exs new file mode 100644 index 0000000000..c111c16697 --- /dev/null +++ b/.formatter.exs @@ -0,0 +1,3 @@ +[ + inputs: ["mix.exs", "{exercises}/**/*.{ex,exs}"] +] diff --git a/exercises/accumulate/accumulate_test.exs b/exercises/accumulate/accumulate_test.exs index fe95d3a5dd..30af979466 100644 --- a/exercises/accumulate/accumulate_test.exs +++ b/exercises/accumulate/accumulate_test.exs @@ -2,30 +2,30 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("accumulate.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule AccumulateTest do use ExUnit.Case test "accumulate empty list" do - assert Accumulate.accumulate([], fn(n) -> n * n end) == [] + assert Accumulate.accumulate([], fn n -> n * n end) == [] end @tag :pending test "accumulate square numbers" do - assert Accumulate.accumulate([1, 2, 3], fn(n) -> n * n end) == [1, 4, 9] + assert Accumulate.accumulate([1, 2, 3], fn n -> n * n end) == [1, 4, 9] end @tag :pending test "accumulate upcased strings" do - fun = fn(w) -> String.upcase(w) end + fun = fn w -> String.upcase(w) end assert Accumulate.accumulate(["hello", "world"], fun) == ["HELLO", "WORLD"] end @tag :pending test "accumulate reversed strings" do - fun = fn(w) -> String.reverse(w) end + fun = fn w -> String.reverse(w) end words = ~w(the quick brown fox etc) expected = ["eht", "kciuq", "nworb", "xof", "cte"] assert Accumulate.accumulate(words, fun) == expected @@ -34,8 +34,8 @@ defmodule AccumulateTest do @tag :pending test "nested accumulate" do chars = ~w(a b c) - nums = ~w(1 2 3) - fun = fn(c) -> Accumulate.accumulate(nums, &(c <> &1)) end + nums = ~w(1 2 3) + fun = fn c -> Accumulate.accumulate(nums, &(c <> &1)) end expected = [["a1", "a2", "a3"], ["b1", "b2", "b3"], ["c1", "c2", "c3"]] assert Accumulate.accumulate(chars, fun) == expected end diff --git a/exercises/acronym/acronym_test.exs b/exercises/acronym/acronym_test.exs index 175d8375cf..cf773155e2 100644 --- a/exercises/acronym/acronym_test.exs +++ b/exercises/acronym/acronym_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("acronym.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule AcronymTest do use ExUnit.Case diff --git a/exercises/acronym/example.exs b/exercises/acronym/example.exs index e5317803f1..bc32ffccb0 100644 --- a/exercises/acronym/example.exs +++ b/exercises/acronym/example.exs @@ -1,11 +1,10 @@ defmodule Acronym do - @spec abbreviate(String.t()) :: String.t() def abbreviate(string) do Regex.scan(~r/[A-Z]+[a-z]*|[a-z]+/, string) - |> List.flatten - |> Enum.map(fn(x) -> String.first(x) end) + |> List.flatten() + |> Enum.map(fn x -> String.first(x) end) |> Enum.join("") - |> String.upcase + |> String.upcase() end end diff --git a/exercises/all-your-base/all-your-base-test.exs b/exercises/all-your-base/all-your-base-test.exs index 3bac7b4f5e..c2afb128cd 100644 --- a/exercises/all-your-base/all-your-base-test.exs +++ b/exercises/all-your-base/all-your-base-test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("all-your-base.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule AllYourBaseTest do use ExUnit.Case diff --git a/exercises/all-your-base/example.exs b/exercises/all-your-base/example.exs index b13516716a..a3132f0229 100644 --- a/exercises/all-your-base/example.exs +++ b/exercises/all-your-base/example.exs @@ -1,5 +1,4 @@ defmodule AllYourBase do - @doc """ Given a number in base a, represented as a sequence of digits, converts it to base b, or returns nil if either of the bases are less than 2 @@ -8,8 +7,9 @@ defmodule AllYourBase do @spec convert(list, integer, integer) :: list def convert(digits, base_a, base_b) do cond do - base_a > 1 and base_b > 1 and digits !=[] -> + base_a > 1 and base_b > 1 and digits != [] -> do_convert(digits, base_a, base_b) + true -> nil end @@ -17,18 +17,25 @@ defmodule AllYourBase do defp do_convert(digits, base_a, base_b) do num = convert_to_num(digits, base_a, 0) + case num do - nil -> nil - 0 -> [0] - num -> convert_to_digits(num, base_b, []) - |> Enum.reverse + nil -> + nil + + 0 -> + [0] + + num -> + convert_to_digits(num, base_b, []) + |> Enum.reverse() end end defp convert_to_num([head | tail], base_a, accumulator) do cond do head < base_a and head >= 0 -> - convert_to_num(tail, base_a, accumulator * base_a + head) + convert_to_num(tail, base_a, accumulator * base_a + head) + true -> nil end diff --git a/exercises/allergies/allergies.exs b/exercises/allergies/allergies.exs index 6f3947a216..1c2999c91d 100644 --- a/exercises/allergies/allergies.exs +++ b/exercises/allergies/allergies.exs @@ -2,16 +2,14 @@ defmodule Allergies do @doc """ List the allergies for which the corresponding flag bit is true. """ - @spec list(non_neg_integer) :: [String.t] + @spec list(non_neg_integer) :: [String.t()] def list(flags) do - end @doc """ Returns whether the corresponding flag bit in 'flags' is set for the item. """ - @spec allergic_to?(non_neg_integer, String.t) :: boolean + @spec allergic_to?(non_neg_integer, String.t()) :: boolean def allergic_to?(flags, item) do - end end diff --git a/exercises/allergies/allergies_test.exs b/exercises/allergies/allergies_test.exs index 69678de6f9..54766a51a3 100644 --- a/exercises/allergies/allergies_test.exs +++ b/exercises/allergies/allergies_test.exs @@ -2,9 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("allergies.exs", __DIR__) end - -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule AllergiesTest do use ExUnit.Case @@ -41,12 +40,16 @@ defmodule AllergiesTest do @tag :pending test "allergic_to_lots_of_stuff" do - Allergies.list(248) |> assert_is_a_set_containing(~w[strawberries tomatoes chocolate pollen cats]) + Allergies.list(248) + |> assert_is_a_set_containing(~w[strawberries tomatoes chocolate pollen cats]) end @tag :pending test "allergic_to_everything" do - Allergies.list(255) |> assert_is_a_set_containing(~w[eggs peanuts shellfish strawberries tomatoes chocolate pollen cats]) + Allergies.list(255) + |> assert_is_a_set_containing( + ~w[eggs peanuts shellfish strawberries tomatoes chocolate pollen cats] + ) end @tag :pending @@ -68,16 +71,19 @@ defmodule AllergiesTest do @tag :pending test "ignore_non_allergen_score_parts" do - Allergies.list(509) |> assert_is_a_set_containing(~w[eggs shellfish strawberries tomatoes chocolate pollen cats]) + Allergies.list(509) + |> assert_is_a_set_containing(~w[eggs shellfish strawberries tomatoes chocolate pollen cats]) end defp assert_is_a_set_containing(list, to_contain) do - set = Enum.into(list, MapSet.new) - same_contents = to_contain - |> Enum.into(MapSet.new) + set = Enum.into(list, MapSet.new()) + + same_contents = + to_contain + |> Enum.into(MapSet.new()) |> MapSet.equal?(set) + assert same_contents, - "Expected a set with: #{inspect to_contain} got #{inspect set |> MapSet.to_list}" + "Expected a set with: #{inspect(to_contain)} got #{inspect(set |> MapSet.to_list())}" end - end diff --git a/exercises/anagram/anagram.exs b/exercises/anagram/anagram.exs index e8e46d9dc5..f5d96bbdd3 100644 --- a/exercises/anagram/anagram.exs +++ b/exercises/anagram/anagram.exs @@ -2,8 +2,7 @@ defmodule Anagram do @doc """ Returns all candidates that are anagrams of, but not equal to, 'base'. """ - @spec match(String.t, [String.t]) :: [String.t] + @spec match(String.t(), [String.t()]) :: [String.t()] def match(base, candidates) do - end end diff --git a/exercises/anagram/anagram_test.exs b/exercises/anagram/anagram_test.exs index 32b1346ccf..58e62e8714 100644 --- a/exercises/anagram/anagram_test.exs +++ b/exercises/anagram/anagram_test.exs @@ -2,75 +2,75 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("anagram.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule AnagramTest do use ExUnit.Case # @tag :pending test "no matches" do - matches = Anagram.match "diaper", ["hello", "world", "zombies", "pants"] + matches = Anagram.match("diaper", ["hello", "world", "zombies", "pants"]) assert matches == [] end @tag :pending test "detect simple anagram" do - matches = Anagram.match "ant", ["tan", "stand", "at"] + matches = Anagram.match("ant", ["tan", "stand", "at"]) assert matches == ["tan"] end @tag :pending test "detect multiple anagrams" do - matches = Anagram.match "master", ["stream", "pigeon", "maters"] + matches = Anagram.match("master", ["stream", "pigeon", "maters"]) assert matches == ["stream", "maters"] end @tag :pending test "do not detect anagram subsets" do - matches = Anagram.match "good", ~w(dog goody) + matches = Anagram.match("good", ~w(dog goody)) assert matches == [] end @tag :pending test "detect anagram" do - matches = Anagram.match "listen", ~w(enlists google inlets banana) + matches = Anagram.match("listen", ~w(enlists google inlets banana)) assert matches == ["inlets"] end @tag :pending test "multiple anagrams" do - matches = Anagram.match "allergy", ~w(gallery ballerina regally clergy largely leading) + matches = Anagram.match("allergy", ~w(gallery ballerina regally clergy largely leading)) assert matches == ["gallery", "regally", "largely"] end @tag :pending test "anagrams must use all letters exactly once" do - matches = Anagram.match "patter", ["tapper"] + matches = Anagram.match("patter", ["tapper"]) assert matches == [] end @tag :pending test "detect anagrams with case-insensitive subject" do - matches = Anagram.match "Orchestra", ~w(cashregister carthorse radishes) + matches = Anagram.match("Orchestra", ~w(cashregister carthorse radishes)) assert matches == ["carthorse"] end @tag :pending test "detect anagrams with case-insensitive candidate" do - matches = Anagram.match "orchestra", ~w(cashregister Carthorse radishes) + matches = Anagram.match("orchestra", ~w(cashregister Carthorse radishes)) assert matches == ["Carthorse"] end @tag :pending test "anagrams must not be the source word" do - matches = Anagram.match "corn", ["corn", "dark", "Corn", "rank", "CORN", "cron", "park"] + matches = Anagram.match("corn", ["corn", "dark", "Corn", "rank", "CORN", "cron", "park"]) assert matches == ["cron"] end @tag :pending test "do not detect words based on checksum" do - matches = Anagram.match "mass", ["last"] + matches = Anagram.match("mass", ["last"]) assert matches == [] end end diff --git a/exercises/anagram/example.exs b/exercises/anagram/example.exs index c24794e235..839c413487 100644 --- a/exercises/anagram/example.exs +++ b/exercises/anagram/example.exs @@ -4,10 +4,11 @@ defmodule Anagram do Comparison is case insensitive. """ - @spec match(String.t, [String.t]) :: [String.t] + @spec match(String.t(), [String.t()]) :: [String.t()] def match(target, words) do lc_target = String.downcase(target) sorted_target = sort(lc_target) + Enum.filter(words, fn word -> lc_word = String.downcase(word) # `and` is shortcutting diff --git a/exercises/atbash-cipher/atbash_cipher.exs b/exercises/atbash-cipher/atbash_cipher.exs index a0cb867624..f81e12124b 100644 --- a/exercises/atbash-cipher/atbash_cipher.exs +++ b/exercises/atbash-cipher/atbash_cipher.exs @@ -7,11 +7,11 @@ defmodule Atbash do iex> Atbash.encode("completely insecure") "xlnko vgvob rmhvx fiv" """ - @spec encode(String.t) :: String.t + @spec encode(String.t()) :: String.t() def encode(plaintext) do end - @spec decode(String.t) :: String.t + @spec decode(String.t()) :: String.t() def decode(cipher) do end end diff --git a/exercises/atbash-cipher/atbash_cipher_test.exs b/exercises/atbash-cipher/atbash_cipher_test.exs index 824d1349b6..944d3a75f5 100644 --- a/exercises/atbash-cipher/atbash_cipher_test.exs +++ b/exercises/atbash-cipher/atbash_cipher_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("atbash_cipher.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule AtbashTest do use ExUnit.Case diff --git a/exercises/bank-account/bank_account_test.exs b/exercises/bank-account/bank_account_test.exs index 59c674e632..ae1f9dddb4 100644 --- a/exercises/bank-account/bank_account_test.exs +++ b/exercises/bank-account/bank_account_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("account.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) # The BankAccount module should support four calls: # @@ -26,8 +26,8 @@ defmodule BankAccountTest do use ExUnit.Case setup do - account = BankAccount.open_bank - { :ok, account: account } + account = BankAccount.open_bank() + {:ok, account: account} end # @tag :pending @@ -59,18 +59,23 @@ defmodule BankAccountTest do end @tag :pending - test "incrementing balance from another process then checking it from test process", %{account: account} do + test "incrementing balance from another process then checking it from test process", %{ + account: account + } do assert BankAccount.balance(account) == 0 this = self() + spawn(fn -> BankAccount.update(account, 20) send(this, :continue) end) + receive do :continue -> :ok after 1000 -> flunk("Timeout") end + assert BankAccount.balance(account) == 20 end end diff --git a/exercises/beer-song/beer_song.exs b/exercises/beer-song/beer_song.exs index 885ccd8253..0fa099d943 100644 --- a/exercises/beer-song/beer_song.exs +++ b/exercises/beer-song/beer_song.exs @@ -2,7 +2,7 @@ defmodule BeerSong do @doc """ Get a single verse of the beer song """ - @spec verse(integer) :: String.t + @spec verse(integer) :: String.t() def verse(number) do # Your implementation here... end @@ -10,7 +10,7 @@ defmodule BeerSong do @doc """ Get the entire beer song for a given range of numbers of bottles. """ - @spec lyrics(Range.t) :: String.t + @spec lyrics(Range.t()) :: String.t() def lyrics(range) do # Your implementation here... end diff --git a/exercises/beer-song/beer_song_test.exs b/exercises/beer-song/beer_song_test.exs index 6b1cafff41..8611c1ca4d 100644 --- a/exercises/beer-song/beer_song_test.exs +++ b/exercises/beer-song/beer_song_test.exs @@ -2,362 +2,362 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("beer_song.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule BeerSongTest do use ExUnit.Case test "getting the first verse (99 bottles)" do assert BeerSong.verse(99) == """ - 99 bottles of beer on the wall, 99 bottles of beer. - Take one down and pass it around, 98 bottles of beer on the wall. - """ + 99 bottles of beer on the wall, 99 bottles of beer. + Take one down and pass it around, 98 bottles of beer on the wall. + """ end @tag :pending test "getting the second verse (98 bottles)" do assert BeerSong.verse(98) == """ - 98 bottles of beer on the wall, 98 bottles of beer. - Take one down and pass it around, 97 bottles of beer on the wall. - """ + 98 bottles of beer on the wall, 98 bottles of beer. + Take one down and pass it around, 97 bottles of beer on the wall. + """ end @tag :pending test "getting just the penultimate verse" do assert BeerSong.verse(1) == """ - 1 bottle of beer on the wall, 1 bottle of beer. - Take it down and pass it around, no more bottles of beer on the wall. - """ + 1 bottle of beer on the wall, 1 bottle of beer. + Take it down and pass it around, no more bottles of beer on the wall. + """ end @tag :pending test "getting just the last verse" do assert BeerSong.verse(0) == """ - No more bottles of beer on the wall, no more bottles of beer. - Go to the store and buy some more, 99 bottles of beer on the wall. - """ + No more bottles of beer on the wall, no more bottles of beer. + Go to the store and buy some more, 99 bottles of beer on the wall. + """ end @tag :pending test "getting the last 4 verses" do assert BeerSong.lyrics(3..0) == """ - 3 bottles of beer on the wall, 3 bottles of beer. - Take one down and pass it around, 2 bottles of beer on the wall. + 3 bottles of beer on the wall, 3 bottles of beer. + Take one down and pass it around, 2 bottles of beer on the wall. - 2 bottles of beer on the wall, 2 bottles of beer. - Take one down and pass it around, 1 bottle of beer on the wall. + 2 bottles of beer on the wall, 2 bottles of beer. + Take one down and pass it around, 1 bottle of beer on the wall. - 1 bottle of beer on the wall, 1 bottle of beer. - Take it down and pass it around, no more bottles of beer on the wall. + 1 bottle of beer on the wall, 1 bottle of beer. + Take it down and pass it around, no more bottles of beer on the wall. - No more bottles of beer on the wall, no more bottles of beer. - Go to the store and buy some more, 99 bottles of beer on the wall. - """ + No more bottles of beer on the wall, no more bottles of beer. + Go to the store and buy some more, 99 bottles of beer on the wall. + """ end @tag :pending test "getting the whole song" do - assert BeerSong.lyrics == """ - 99 bottles of beer on the wall, 99 bottles of beer. - Take one down and pass it around, 98 bottles of beer on the wall. + assert BeerSong.lyrics() == """ + 99 bottles of beer on the wall, 99 bottles of beer. + Take one down and pass it around, 98 bottles of beer on the wall. - 98 bottles of beer on the wall, 98 bottles of beer. - Take one down and pass it around, 97 bottles of beer on the wall. + 98 bottles of beer on the wall, 98 bottles of beer. + Take one down and pass it around, 97 bottles of beer on the wall. - 97 bottles of beer on the wall, 97 bottles of beer. - Take one down and pass it around, 96 bottles of beer on the wall. + 97 bottles of beer on the wall, 97 bottles of beer. + Take one down and pass it around, 96 bottles of beer on the wall. - 96 bottles of beer on the wall, 96 bottles of beer. - Take one down and pass it around, 95 bottles of beer on the wall. + 96 bottles of beer on the wall, 96 bottles of beer. + Take one down and pass it around, 95 bottles of beer on the wall. - 95 bottles of beer on the wall, 95 bottles of beer. - Take one down and pass it around, 94 bottles of beer on the wall. + 95 bottles of beer on the wall, 95 bottles of beer. + Take one down and pass it around, 94 bottles of beer on the wall. - 94 bottles of beer on the wall, 94 bottles of beer. - Take one down and pass it around, 93 bottles of beer on the wall. + 94 bottles of beer on the wall, 94 bottles of beer. + Take one down and pass it around, 93 bottles of beer on the wall. - 93 bottles of beer on the wall, 93 bottles of beer. - Take one down and pass it around, 92 bottles of beer on the wall. + 93 bottles of beer on the wall, 93 bottles of beer. + Take one down and pass it around, 92 bottles of beer on the wall. - 92 bottles of beer on the wall, 92 bottles of beer. - Take one down and pass it around, 91 bottles of beer on the wall. + 92 bottles of beer on the wall, 92 bottles of beer. + Take one down and pass it around, 91 bottles of beer on the wall. - 91 bottles of beer on the wall, 91 bottles of beer. - Take one down and pass it around, 90 bottles of beer on the wall. + 91 bottles of beer on the wall, 91 bottles of beer. + Take one down and pass it around, 90 bottles of beer on the wall. - 90 bottles of beer on the wall, 90 bottles of beer. - Take one down and pass it around, 89 bottles of beer on the wall. + 90 bottles of beer on the wall, 90 bottles of beer. + Take one down and pass it around, 89 bottles of beer on the wall. - 89 bottles of beer on the wall, 89 bottles of beer. - Take one down and pass it around, 88 bottles of beer on the wall. + 89 bottles of beer on the wall, 89 bottles of beer. + Take one down and pass it around, 88 bottles of beer on the wall. - 88 bottles of beer on the wall, 88 bottles of beer. - Take one down and pass it around, 87 bottles of beer on the wall. + 88 bottles of beer on the wall, 88 bottles of beer. + Take one down and pass it around, 87 bottles of beer on the wall. - 87 bottles of beer on the wall, 87 bottles of beer. - Take one down and pass it around, 86 bottles of beer on the wall. + 87 bottles of beer on the wall, 87 bottles of beer. + Take one down and pass it around, 86 bottles of beer on the wall. - 86 bottles of beer on the wall, 86 bottles of beer. - Take one down and pass it around, 85 bottles of beer on the wall. + 86 bottles of beer on the wall, 86 bottles of beer. + Take one down and pass it around, 85 bottles of beer on the wall. - 85 bottles of beer on the wall, 85 bottles of beer. - Take one down and pass it around, 84 bottles of beer on the wall. + 85 bottles of beer on the wall, 85 bottles of beer. + Take one down and pass it around, 84 bottles of beer on the wall. - 84 bottles of beer on the wall, 84 bottles of beer. - Take one down and pass it around, 83 bottles of beer on the wall. + 84 bottles of beer on the wall, 84 bottles of beer. + Take one down and pass it around, 83 bottles of beer on the wall. - 83 bottles of beer on the wall, 83 bottles of beer. - Take one down and pass it around, 82 bottles of beer on the wall. + 83 bottles of beer on the wall, 83 bottles of beer. + Take one down and pass it around, 82 bottles of beer on the wall. - 82 bottles of beer on the wall, 82 bottles of beer. - Take one down and pass it around, 81 bottles of beer on the wall. + 82 bottles of beer on the wall, 82 bottles of beer. + Take one down and pass it around, 81 bottles of beer on the wall. - 81 bottles of beer on the wall, 81 bottles of beer. - Take one down and pass it around, 80 bottles of beer on the wall. + 81 bottles of beer on the wall, 81 bottles of beer. + Take one down and pass it around, 80 bottles of beer on the wall. - 80 bottles of beer on the wall, 80 bottles of beer. - Take one down and pass it around, 79 bottles of beer on the wall. + 80 bottles of beer on the wall, 80 bottles of beer. + Take one down and pass it around, 79 bottles of beer on the wall. - 79 bottles of beer on the wall, 79 bottles of beer. - Take one down and pass it around, 78 bottles of beer on the wall. + 79 bottles of beer on the wall, 79 bottles of beer. + Take one down and pass it around, 78 bottles of beer on the wall. - 78 bottles of beer on the wall, 78 bottles of beer. - Take one down and pass it around, 77 bottles of beer on the wall. + 78 bottles of beer on the wall, 78 bottles of beer. + Take one down and pass it around, 77 bottles of beer on the wall. - 77 bottles of beer on the wall, 77 bottles of beer. - Take one down and pass it around, 76 bottles of beer on the wall. + 77 bottles of beer on the wall, 77 bottles of beer. + Take one down and pass it around, 76 bottles of beer on the wall. - 76 bottles of beer on the wall, 76 bottles of beer. - Take one down and pass it around, 75 bottles of beer on the wall. + 76 bottles of beer on the wall, 76 bottles of beer. + Take one down and pass it around, 75 bottles of beer on the wall. - 75 bottles of beer on the wall, 75 bottles of beer. - Take one down and pass it around, 74 bottles of beer on the wall. + 75 bottles of beer on the wall, 75 bottles of beer. + Take one down and pass it around, 74 bottles of beer on the wall. - 74 bottles of beer on the wall, 74 bottles of beer. - Take one down and pass it around, 73 bottles of beer on the wall. + 74 bottles of beer on the wall, 74 bottles of beer. + Take one down and pass it around, 73 bottles of beer on the wall. - 73 bottles of beer on the wall, 73 bottles of beer. - Take one down and pass it around, 72 bottles of beer on the wall. + 73 bottles of beer on the wall, 73 bottles of beer. + Take one down and pass it around, 72 bottles of beer on the wall. - 72 bottles of beer on the wall, 72 bottles of beer. - Take one down and pass it around, 71 bottles of beer on the wall. + 72 bottles of beer on the wall, 72 bottles of beer. + Take one down and pass it around, 71 bottles of beer on the wall. - 71 bottles of beer on the wall, 71 bottles of beer. - Take one down and pass it around, 70 bottles of beer on the wall. + 71 bottles of beer on the wall, 71 bottles of beer. + Take one down and pass it around, 70 bottles of beer on the wall. - 70 bottles of beer on the wall, 70 bottles of beer. - Take one down and pass it around, 69 bottles of beer on the wall. + 70 bottles of beer on the wall, 70 bottles of beer. + Take one down and pass it around, 69 bottles of beer on the wall. - 69 bottles of beer on the wall, 69 bottles of beer. - Take one down and pass it around, 68 bottles of beer on the wall. + 69 bottles of beer on the wall, 69 bottles of beer. + Take one down and pass it around, 68 bottles of beer on the wall. - 68 bottles of beer on the wall, 68 bottles of beer. - Take one down and pass it around, 67 bottles of beer on the wall. + 68 bottles of beer on the wall, 68 bottles of beer. + Take one down and pass it around, 67 bottles of beer on the wall. - 67 bottles of beer on the wall, 67 bottles of beer. - Take one down and pass it around, 66 bottles of beer on the wall. + 67 bottles of beer on the wall, 67 bottles of beer. + Take one down and pass it around, 66 bottles of beer on the wall. - 66 bottles of beer on the wall, 66 bottles of beer. - Take one down and pass it around, 65 bottles of beer on the wall. + 66 bottles of beer on the wall, 66 bottles of beer. + Take one down and pass it around, 65 bottles of beer on the wall. - 65 bottles of beer on the wall, 65 bottles of beer. - Take one down and pass it around, 64 bottles of beer on the wall. + 65 bottles of beer on the wall, 65 bottles of beer. + Take one down and pass it around, 64 bottles of beer on the wall. - 64 bottles of beer on the wall, 64 bottles of beer. - Take one down and pass it around, 63 bottles of beer on the wall. + 64 bottles of beer on the wall, 64 bottles of beer. + Take one down and pass it around, 63 bottles of beer on the wall. - 63 bottles of beer on the wall, 63 bottles of beer. - Take one down and pass it around, 62 bottles of beer on the wall. + 63 bottles of beer on the wall, 63 bottles of beer. + Take one down and pass it around, 62 bottles of beer on the wall. - 62 bottles of beer on the wall, 62 bottles of beer. - Take one down and pass it around, 61 bottles of beer on the wall. + 62 bottles of beer on the wall, 62 bottles of beer. + Take one down and pass it around, 61 bottles of beer on the wall. - 61 bottles of beer on the wall, 61 bottles of beer. - Take one down and pass it around, 60 bottles of beer on the wall. + 61 bottles of beer on the wall, 61 bottles of beer. + Take one down and pass it around, 60 bottles of beer on the wall. - 60 bottles of beer on the wall, 60 bottles of beer. - Take one down and pass it around, 59 bottles of beer on the wall. + 60 bottles of beer on the wall, 60 bottles of beer. + Take one down and pass it around, 59 bottles of beer on the wall. - 59 bottles of beer on the wall, 59 bottles of beer. - Take one down and pass it around, 58 bottles of beer on the wall. + 59 bottles of beer on the wall, 59 bottles of beer. + Take one down and pass it around, 58 bottles of beer on the wall. - 58 bottles of beer on the wall, 58 bottles of beer. - Take one down and pass it around, 57 bottles of beer on the wall. + 58 bottles of beer on the wall, 58 bottles of beer. + Take one down and pass it around, 57 bottles of beer on the wall. - 57 bottles of beer on the wall, 57 bottles of beer. - Take one down and pass it around, 56 bottles of beer on the wall. + 57 bottles of beer on the wall, 57 bottles of beer. + Take one down and pass it around, 56 bottles of beer on the wall. - 56 bottles of beer on the wall, 56 bottles of beer. - Take one down and pass it around, 55 bottles of beer on the wall. + 56 bottles of beer on the wall, 56 bottles of beer. + Take one down and pass it around, 55 bottles of beer on the wall. - 55 bottles of beer on the wall, 55 bottles of beer. - Take one down and pass it around, 54 bottles of beer on the wall. + 55 bottles of beer on the wall, 55 bottles of beer. + Take one down and pass it around, 54 bottles of beer on the wall. - 54 bottles of beer on the wall, 54 bottles of beer. - Take one down and pass it around, 53 bottles of beer on the wall. + 54 bottles of beer on the wall, 54 bottles of beer. + Take one down and pass it around, 53 bottles of beer on the wall. - 53 bottles of beer on the wall, 53 bottles of beer. - Take one down and pass it around, 52 bottles of beer on the wall. + 53 bottles of beer on the wall, 53 bottles of beer. + Take one down and pass it around, 52 bottles of beer on the wall. - 52 bottles of beer on the wall, 52 bottles of beer. - Take one down and pass it around, 51 bottles of beer on the wall. + 52 bottles of beer on the wall, 52 bottles of beer. + Take one down and pass it around, 51 bottles of beer on the wall. - 51 bottles of beer on the wall, 51 bottles of beer. - Take one down and pass it around, 50 bottles of beer on the wall. + 51 bottles of beer on the wall, 51 bottles of beer. + Take one down and pass it around, 50 bottles of beer on the wall. - 50 bottles of beer on the wall, 50 bottles of beer. - Take one down and pass it around, 49 bottles of beer on the wall. + 50 bottles of beer on the wall, 50 bottles of beer. + Take one down and pass it around, 49 bottles of beer on the wall. - 49 bottles of beer on the wall, 49 bottles of beer. - Take one down and pass it around, 48 bottles of beer on the wall. + 49 bottles of beer on the wall, 49 bottles of beer. + Take one down and pass it around, 48 bottles of beer on the wall. - 48 bottles of beer on the wall, 48 bottles of beer. - Take one down and pass it around, 47 bottles of beer on the wall. + 48 bottles of beer on the wall, 48 bottles of beer. + Take one down and pass it around, 47 bottles of beer on the wall. - 47 bottles of beer on the wall, 47 bottles of beer. - Take one down and pass it around, 46 bottles of beer on the wall. + 47 bottles of beer on the wall, 47 bottles of beer. + Take one down and pass it around, 46 bottles of beer on the wall. - 46 bottles of beer on the wall, 46 bottles of beer. - Take one down and pass it around, 45 bottles of beer on the wall. + 46 bottles of beer on the wall, 46 bottles of beer. + Take one down and pass it around, 45 bottles of beer on the wall. - 45 bottles of beer on the wall, 45 bottles of beer. - Take one down and pass it around, 44 bottles of beer on the wall. + 45 bottles of beer on the wall, 45 bottles of beer. + Take one down and pass it around, 44 bottles of beer on the wall. - 44 bottles of beer on the wall, 44 bottles of beer. - Take one down and pass it around, 43 bottles of beer on the wall. + 44 bottles of beer on the wall, 44 bottles of beer. + Take one down and pass it around, 43 bottles of beer on the wall. - 43 bottles of beer on the wall, 43 bottles of beer. - Take one down and pass it around, 42 bottles of beer on the wall. + 43 bottles of beer on the wall, 43 bottles of beer. + Take one down and pass it around, 42 bottles of beer on the wall. - 42 bottles of beer on the wall, 42 bottles of beer. - Take one down and pass it around, 41 bottles of beer on the wall. + 42 bottles of beer on the wall, 42 bottles of beer. + Take one down and pass it around, 41 bottles of beer on the wall. - 41 bottles of beer on the wall, 41 bottles of beer. - Take one down and pass it around, 40 bottles of beer on the wall. + 41 bottles of beer on the wall, 41 bottles of beer. + Take one down and pass it around, 40 bottles of beer on the wall. - 40 bottles of beer on the wall, 40 bottles of beer. - Take one down and pass it around, 39 bottles of beer on the wall. + 40 bottles of beer on the wall, 40 bottles of beer. + Take one down and pass it around, 39 bottles of beer on the wall. - 39 bottles of beer on the wall, 39 bottles of beer. - Take one down and pass it around, 38 bottles of beer on the wall. + 39 bottles of beer on the wall, 39 bottles of beer. + Take one down and pass it around, 38 bottles of beer on the wall. - 38 bottles of beer on the wall, 38 bottles of beer. - Take one down and pass it around, 37 bottles of beer on the wall. + 38 bottles of beer on the wall, 38 bottles of beer. + Take one down and pass it around, 37 bottles of beer on the wall. - 37 bottles of beer on the wall, 37 bottles of beer. - Take one down and pass it around, 36 bottles of beer on the wall. + 37 bottles of beer on the wall, 37 bottles of beer. + Take one down and pass it around, 36 bottles of beer on the wall. - 36 bottles of beer on the wall, 36 bottles of beer. - Take one down and pass it around, 35 bottles of beer on the wall. + 36 bottles of beer on the wall, 36 bottles of beer. + Take one down and pass it around, 35 bottles of beer on the wall. - 35 bottles of beer on the wall, 35 bottles of beer. - Take one down and pass it around, 34 bottles of beer on the wall. + 35 bottles of beer on the wall, 35 bottles of beer. + Take one down and pass it around, 34 bottles of beer on the wall. - 34 bottles of beer on the wall, 34 bottles of beer. - Take one down and pass it around, 33 bottles of beer on the wall. + 34 bottles of beer on the wall, 34 bottles of beer. + Take one down and pass it around, 33 bottles of beer on the wall. - 33 bottles of beer on the wall, 33 bottles of beer. - Take one down and pass it around, 32 bottles of beer on the wall. + 33 bottles of beer on the wall, 33 bottles of beer. + Take one down and pass it around, 32 bottles of beer on the wall. - 32 bottles of beer on the wall, 32 bottles of beer. - Take one down and pass it around, 31 bottles of beer on the wall. + 32 bottles of beer on the wall, 32 bottles of beer. + Take one down and pass it around, 31 bottles of beer on the wall. - 31 bottles of beer on the wall, 31 bottles of beer. - Take one down and pass it around, 30 bottles of beer on the wall. + 31 bottles of beer on the wall, 31 bottles of beer. + Take one down and pass it around, 30 bottles of beer on the wall. - 30 bottles of beer on the wall, 30 bottles of beer. - Take one down and pass it around, 29 bottles of beer on the wall. + 30 bottles of beer on the wall, 30 bottles of beer. + Take one down and pass it around, 29 bottles of beer on the wall. - 29 bottles of beer on the wall, 29 bottles of beer. - Take one down and pass it around, 28 bottles of beer on the wall. + 29 bottles of beer on the wall, 29 bottles of beer. + Take one down and pass it around, 28 bottles of beer on the wall. - 28 bottles of beer on the wall, 28 bottles of beer. - Take one down and pass it around, 27 bottles of beer on the wall. + 28 bottles of beer on the wall, 28 bottles of beer. + Take one down and pass it around, 27 bottles of beer on the wall. - 27 bottles of beer on the wall, 27 bottles of beer. - Take one down and pass it around, 26 bottles of beer on the wall. + 27 bottles of beer on the wall, 27 bottles of beer. + Take one down and pass it around, 26 bottles of beer on the wall. - 26 bottles of beer on the wall, 26 bottles of beer. - Take one down and pass it around, 25 bottles of beer on the wall. + 26 bottles of beer on the wall, 26 bottles of beer. + Take one down and pass it around, 25 bottles of beer on the wall. - 25 bottles of beer on the wall, 25 bottles of beer. - Take one down and pass it around, 24 bottles of beer on the wall. + 25 bottles of beer on the wall, 25 bottles of beer. + Take one down and pass it around, 24 bottles of beer on the wall. - 24 bottles of beer on the wall, 24 bottles of beer. - Take one down and pass it around, 23 bottles of beer on the wall. + 24 bottles of beer on the wall, 24 bottles of beer. + Take one down and pass it around, 23 bottles of beer on the wall. - 23 bottles of beer on the wall, 23 bottles of beer. - Take one down and pass it around, 22 bottles of beer on the wall. + 23 bottles of beer on the wall, 23 bottles of beer. + Take one down and pass it around, 22 bottles of beer on the wall. - 22 bottles of beer on the wall, 22 bottles of beer. - Take one down and pass it around, 21 bottles of beer on the wall. + 22 bottles of beer on the wall, 22 bottles of beer. + Take one down and pass it around, 21 bottles of beer on the wall. - 21 bottles of beer on the wall, 21 bottles of beer. - Take one down and pass it around, 20 bottles of beer on the wall. + 21 bottles of beer on the wall, 21 bottles of beer. + Take one down and pass it around, 20 bottles of beer on the wall. - 20 bottles of beer on the wall, 20 bottles of beer. - Take one down and pass it around, 19 bottles of beer on the wall. + 20 bottles of beer on the wall, 20 bottles of beer. + Take one down and pass it around, 19 bottles of beer on the wall. - 19 bottles of beer on the wall, 19 bottles of beer. - Take one down and pass it around, 18 bottles of beer on the wall. + 19 bottles of beer on the wall, 19 bottles of beer. + Take one down and pass it around, 18 bottles of beer on the wall. - 18 bottles of beer on the wall, 18 bottles of beer. - Take one down and pass it around, 17 bottles of beer on the wall. + 18 bottles of beer on the wall, 18 bottles of beer. + Take one down and pass it around, 17 bottles of beer on the wall. - 17 bottles of beer on the wall, 17 bottles of beer. - Take one down and pass it around, 16 bottles of beer on the wall. + 17 bottles of beer on the wall, 17 bottles of beer. + Take one down and pass it around, 16 bottles of beer on the wall. - 16 bottles of beer on the wall, 16 bottles of beer. - Take one down and pass it around, 15 bottles of beer on the wall. + 16 bottles of beer on the wall, 16 bottles of beer. + Take one down and pass it around, 15 bottles of beer on the wall. - 15 bottles of beer on the wall, 15 bottles of beer. - Take one down and pass it around, 14 bottles of beer on the wall. + 15 bottles of beer on the wall, 15 bottles of beer. + Take one down and pass it around, 14 bottles of beer on the wall. - 14 bottles of beer on the wall, 14 bottles of beer. - Take one down and pass it around, 13 bottles of beer on the wall. + 14 bottles of beer on the wall, 14 bottles of beer. + Take one down and pass it around, 13 bottles of beer on the wall. - 13 bottles of beer on the wall, 13 bottles of beer. - Take one down and pass it around, 12 bottles of beer on the wall. + 13 bottles of beer on the wall, 13 bottles of beer. + Take one down and pass it around, 12 bottles of beer on the wall. - 12 bottles of beer on the wall, 12 bottles of beer. - Take one down and pass it around, 11 bottles of beer on the wall. + 12 bottles of beer on the wall, 12 bottles of beer. + Take one down and pass it around, 11 bottles of beer on the wall. - 11 bottles of beer on the wall, 11 bottles of beer. - Take one down and pass it around, 10 bottles of beer on the wall. + 11 bottles of beer on the wall, 11 bottles of beer. + Take one down and pass it around, 10 bottles of beer on the wall. - 10 bottles of beer on the wall, 10 bottles of beer. - Take one down and pass it around, 9 bottles of beer on the wall. + 10 bottles of beer on the wall, 10 bottles of beer. + Take one down and pass it around, 9 bottles of beer on the wall. - 9 bottles of beer on the wall, 9 bottles of beer. - Take one down and pass it around, 8 bottles of beer on the wall. + 9 bottles of beer on the wall, 9 bottles of beer. + Take one down and pass it around, 8 bottles of beer on the wall. - 8 bottles of beer on the wall, 8 bottles of beer. - Take one down and pass it around, 7 bottles of beer on the wall. + 8 bottles of beer on the wall, 8 bottles of beer. + Take one down and pass it around, 7 bottles of beer on the wall. - 7 bottles of beer on the wall, 7 bottles of beer. - Take one down and pass it around, 6 bottles of beer on the wall. + 7 bottles of beer on the wall, 7 bottles of beer. + Take one down and pass it around, 6 bottles of beer on the wall. - 6 bottles of beer on the wall, 6 bottles of beer. - Take one down and pass it around, 5 bottles of beer on the wall. + 6 bottles of beer on the wall, 6 bottles of beer. + Take one down and pass it around, 5 bottles of beer on the wall. - 5 bottles of beer on the wall, 5 bottles of beer. - Take one down and pass it around, 4 bottles of beer on the wall. + 5 bottles of beer on the wall, 5 bottles of beer. + Take one down and pass it around, 4 bottles of beer on the wall. - 4 bottles of beer on the wall, 4 bottles of beer. - Take one down and pass it around, 3 bottles of beer on the wall. + 4 bottles of beer on the wall, 4 bottles of beer. + Take one down and pass it around, 3 bottles of beer on the wall. - 3 bottles of beer on the wall, 3 bottles of beer. - Take one down and pass it around, 2 bottles of beer on the wall. + 3 bottles of beer on the wall, 3 bottles of beer. + Take one down and pass it around, 2 bottles of beer on the wall. - 2 bottles of beer on the wall, 2 bottles of beer. - Take one down and pass it around, 1 bottle of beer on the wall. + 2 bottles of beer on the wall, 2 bottles of beer. + Take one down and pass it around, 1 bottle of beer on the wall. - 1 bottle of beer on the wall, 1 bottle of beer. - Take it down and pass it around, no more bottles of beer on the wall. + 1 bottle of beer on the wall, 1 bottle of beer. + Take it down and pass it around, no more bottles of beer on the wall. - No more bottles of beer on the wall, no more bottles of beer. - Go to the store and buy some more, 99 bottles of beer on the wall. - """ + No more bottles of beer on the wall, no more bottles of beer. + Go to the store and buy some more, 99 bottles of beer on the wall. + """ end end diff --git a/exercises/beer-song/example.exs b/exercises/beer-song/example.exs index 659dea7adc..6fb7604b96 100644 --- a/exercises/beer-song/example.exs +++ b/exercises/beer-song/example.exs @@ -12,12 +12,14 @@ defmodule BeerSong do end def verse(number) do - "#{number} bottles of beer on the wall, #{number} bottles of beer.\nTake one down and pass it around, #{number - 1} bottles of beer on the wall.\n" + "#{number} bottles of beer on the wall, #{number} bottles of beer.\nTake one down and pass it around, #{ + number - 1 + } bottles of beer on the wall.\n" end def lyrics(range \\ 99..0) do range - |> Enum.map(&verse/1) - |> Enum.join("\n") + |> Enum.map(&verse/1) + |> Enum.join("\n") end end diff --git a/exercises/binary-search-tree/binary_search_tree_test.exs b/exercises/binary-search-tree/binary_search_tree_test.exs index 121edb48d0..ad2c738980 100644 --- a/exercises/binary-search-tree/binary_search_tree_test.exs +++ b/exercises/binary-search-tree/binary_search_tree_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("binary_search_tree.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule BinarySearchTreeTest do use ExUnit.Case diff --git a/exercises/binary-search-tree/example.exs b/exercises/binary-search-tree/example.exs index 1d685002a8..6ab21dbab3 100644 --- a/exercises/binary-search-tree/example.exs +++ b/exercises/binary-search-tree/example.exs @@ -14,7 +14,7 @@ defmodule BinarySearchTree do end def in_order(tree) do - in_order(tree, []) |> Enum.reverse + in_order(tree, []) |> Enum.reverse() end def in_order(nil, accum) do diff --git a/exercises/binary-search/binary_search.exs b/exercises/binary-search/binary_search.exs index b5d3893132..fce2001210 100644 --- a/exercises/binary-search/binary_search.exs +++ b/exercises/binary-search/binary_search.exs @@ -19,6 +19,5 @@ defmodule BinarySearch do @spec search(tuple, integer) :: {:ok, integer} | :not_found def search(numbers, key) do - end end diff --git a/exercises/binary-search/binary_search_test.exs b/exercises/binary-search/binary_search_test.exs index a2b5e59998..4976f54a94 100644 --- a/exercises/binary-search/binary_search_test.exs +++ b/exercises/binary-search/binary_search_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("binary_search.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule BinarySearchTest do use ExUnit.Case diff --git a/exercises/binary-search/example.exs b/exercises/binary-search/example.exs index 3fe51132a6..a93467999b 100644 --- a/exercises/binary-search/example.exs +++ b/exercises/binary-search/example.exs @@ -19,11 +19,13 @@ defmodule BinarySearch do @spec search(tuple, integer) :: {:ok, integer} | :not_found def search({}, _key), do: :not_found + def search(numbers, key) do do_search(numbers, key, 0, tuple_size(numbers) - 1) end defp do_search(_numbers, _key, low, high) when high < low, do: :not_found + defp do_search(numbers, key, low, high) do middle = div(low + high, 2) middle_value = elem(numbers, middle) @@ -31,7 +33,7 @@ defmodule BinarySearch do cond do key < middle_value -> do_search(numbers, key, low, middle - 1) key > middle_value -> do_search(numbers, key, middle + 1, high) - true -> {:ok, middle} + true -> {:ok, middle} end end end diff --git a/exercises/binary/binary.exs b/exercises/binary/binary.exs index 3e41bd931c..d3afc2f60e 100644 --- a/exercises/binary/binary.exs +++ b/exercises/binary/binary.exs @@ -4,7 +4,7 @@ defmodule Binary do On errors returns 0. """ - @spec to_decimal(String.t) :: non_neg_integer + @spec to_decimal(String.t()) :: non_neg_integer def to_decimal(string) do end end diff --git a/exercises/binary/binary_test.exs b/exercises/binary/binary_test.exs index 88836d5aef..585ba26dbe 100644 --- a/exercises/binary/binary_test.exs +++ b/exercises/binary/binary_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("binary.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule BinaryTest do use ExUnit.Case diff --git a/exercises/binary/example.exs b/exercises/binary/example.exs index 9a1776c49a..0054c59ddc 100644 --- a/exercises/binary/example.exs +++ b/exercises/binary/example.exs @@ -1,7 +1,7 @@ defmodule Binary do def to_decimal(string) do if !String.match?(string, ~r{[^10]}) do - string |> bits |> Enum.reverse |> Enum.with_index |> sum + string |> bits |> Enum.reverse() |> Enum.with_index() |> sum else 0 end @@ -9,7 +9,7 @@ defmodule Binary do defp bits(string), do: Enum.map(Regex.scan(~r{[10]}, string), &(&1 == ["1"])) - defp sum(bits), do: Enum.reduce(bits, 0, fn(bit, acc) -> acc + power_of_two(bit) end) + defp sum(bits), do: Enum.reduce(bits, 0, fn bit, acc -> acc + power_of_two(bit) end) defp power_of_two({false, _}), do: 0 defp power_of_two({true, exponent}), do: :math.pow(2, exponent) diff --git a/exercises/bob/bob.exs b/exercises/bob/bob.exs index f83ce5d633..8a6d5a6b21 100644 --- a/exercises/bob/bob.exs +++ b/exercises/bob/bob.exs @@ -1,8 +1,7 @@ defmodule Bob do def hey(input) do cond do - true -> raise "Your implementation goes here" - + true -> raise "Your implementation goes here" end end end diff --git a/exercises/bob/bob_test.exs b/exercises/bob/bob_test.exs index 44457364c4..351dcf30dd 100644 --- a/exercises/bob/bob_test.exs +++ b/exercises/bob/bob_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("bob.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule BobTest do use ExUnit.Case diff --git a/exercises/bowling/bowling.exs b/exercises/bowling/bowling.exs index 0f63fc0494..b46de7ab8a 100644 --- a/exercises/bowling/bowling.exs +++ b/exercises/bowling/bowling.exs @@ -1,5 +1,4 @@ defmodule Bowling do - @doc """ Creates a new game of bowling that can be used to store the results of the game @@ -15,7 +14,7 @@ defmodule Bowling do case it returns a helpful message. """ - @spec roll(any, integer) :: any | String.t + @spec roll(any, integer) :: any | String.t() def roll(game, roll) do end @@ -24,7 +23,7 @@ defmodule Bowling do If the game isn't complete, it returns a helpful message. """ - @spec score(any) :: integer | String.t + @spec score(any) :: integer | String.t() def score(game) do end end diff --git a/exercises/bowling/bowling_test.exs b/exercises/bowling/bowling_test.exs index 6cc0bacc07..e0a2be0157 100644 --- a/exercises/bowling/bowling_test.exs +++ b/exercises/bowling/bowling_test.exs @@ -2,379 +2,195 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("bowling.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule BowlingTest do use ExUnit.Case defp roll_reduce(game, rolls) do - Enum.reduce(rolls, game, fn(roll, game) -> Bowling.roll(game, roll) end) + Enum.reduce(rolls, game, fn roll, game -> Bowling.roll(game, roll) end) end test "should be able to score a game with all zeros" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] game = roll_reduce(game, rolls) assert Bowling.score(game) == 0 end @tag :pending test "should be able to score a game with no strikes or spares" do - game = Bowling.start - rolls = [3, 6, - 3, 6, - 3, 6, - 3, 6, - 3, 6, - 3, 6, - 3, 6, - 3, 6, - 3, 6, - 3, 6] + game = Bowling.start() + rolls = [3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6, 3, 6] game = roll_reduce(game, rolls) assert Bowling.score(game) == 90 end @tag :pending test "a spare followed by zeros is worth ten points" do - game = Bowling.start - rolls = [6, 4, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0] + game = Bowling.start() + rolls = [6, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] game = roll_reduce(game, rolls) assert Bowling.score(game) == 10 end @tag :pending test "points scored in the roll after a spare are counted twice" do - game = Bowling.start - rolls = [6, 4, - 3, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0] + game = Bowling.start() + rolls = [6, 4, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] game = roll_reduce(game, rolls) assert Bowling.score(game) == 16 end @tag :pending test "consecutive spares each get a one roll bonus" do - game = Bowling.start - rolls = [5, 5, - 3, 7, - 4, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0] + game = Bowling.start() + rolls = [5, 5, 3, 7, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] game = roll_reduce(game, rolls) assert Bowling.score(game) == 31 end @tag :pending test "a spare in the last frame gets a one roll bonus that is counted once" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 7, 3, - 7] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 7] game = roll_reduce(game, rolls) assert Bowling.score(game) == 17 end @tag :pending test "a strike earns ten points in a frame with a single roll" do - game = Bowling.start - rolls = [10, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0] + game = Bowling.start() + rolls = [10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] game = roll_reduce(game, rolls) assert Bowling.score(game) == 10 end @tag :pending test "points scored in the two rolls after a strike are counted twice as a bonus" do - game = Bowling.start - rolls = [10, - 5, 3, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0] + game = Bowling.start() + rolls = [10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] game = roll_reduce(game, rolls) assert Bowling.score(game) == 26 end @tag :pending test "consecutive strikes each get the two roll bonus" do - game = Bowling.start - rolls = [10, - 10, - 10, - 5, 3, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0] + game = Bowling.start() + rolls = [10, 10, 10, 5, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] game = roll_reduce(game, rolls) assert Bowling.score(game) == 81 end @tag :pending test "a strike in the last frame gets a two roll bonus that is counted once" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 10, - 7, 1] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 1] game = roll_reduce(game, rolls) assert Bowling.score(game) == 18 end @tag :pending test "rolling a spare with the two roll bonus does not get a bonus roll" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 10, - 7, 3] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 7, 3] game = roll_reduce(game, rolls) assert Bowling.score(game) == 20 end @tag :pending test "strikes with the two roll bonus do not get bonus rolls" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 10, - 10, - 10] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 10] game = roll_reduce(game, rolls) assert Bowling.score(game) == 30 end @tag :pending test "a strike with the one roll bonus after a spare in the last frame does not get a bonus" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 7, 3, - 10] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3, 10] game = roll_reduce(game, rolls) assert Bowling.score(game) == 20 end @tag :pending test "all strikes is a perfect game" do - game = Bowling.start - rolls = [10, - 10, - 10, - 10, - 10, - 10, - 10, - 10, - 10, - 10, - 10, - 10] + game = Bowling.start() + rolls = [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10] game = roll_reduce(game, rolls) assert Bowling.score(game) == 300 end @tag :pending test "rolls cannot score negative points" do - game = Bowling.start + game = Bowling.start() assert Bowling.roll(game, -1) == {:error, "Negative roll is invalid"} end @tag :pending test "a roll cannot score more than 10 points" do - game = Bowling.start + game = Bowling.start() assert Bowling.roll(game, 11) == {:error, "Pin count exceeds pins on the lane"} end @tag :pending test "two rolls in a frame cannot score more than 10 points" do - game = Bowling.start + game = Bowling.start() game = Bowling.roll(game, 5) assert Bowling.roll(game, 6) == {:error, "Pin count exceeds pins on the lane"} end @tag :pending test "bonus roll after a strike in the last frame cannot score more than 10 points" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 10] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10] game = roll_reduce(game, rolls) assert Bowling.roll(game, 11) == {:error, "Pin count exceeds pins on the lane"} end @tag :pending test "two bonus rolls after a strike in the last frame cannot score more than 10 points" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 10, - 5] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 5] game = roll_reduce(game, rolls) assert Bowling.roll(game, 6) == {:error, "Pin count exceeds pins on the lane"} end @tag :pending test "two bonus rolls after a strike in the last frame can score more than 10 points if one is a strike" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 10, - 10, - 6] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10, 6] game = roll_reduce(game, rolls) assert Bowling.score(game) == 26 end @tag :pending test "the second bonus rolls after a strike in the last frame cannot be a strike if the first one is not a strike" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 10, - 6] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 6] game = roll_reduce(game, rolls) assert Bowling.roll(game, 10) == {:error, "Pin count exceeds pins on the lane"} end @tag :pending test "second bonus roll after a strike in the last frame cannot score more than 10 points" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 10, - 10] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10] game = roll_reduce(game, rolls) assert Bowling.roll(game, 11) == {:error, "Pin count exceeds pins on the lane"} end @tag :pending test "an unstarted game cannot be scored" do - game = Bowling.start + game = Bowling.start() assert Bowling.score(game) == {:error, "Score cannot be taken until the end of the game"} end @tag :pending test "an incomplete game cannot be scored" do - game = Bowling.start + game = Bowling.start() rolls = [0, 0] game = roll_reduce(game, rolls) assert Bowling.score(game) == {:error, "Score cannot be taken until the end of the game"} @@ -382,69 +198,32 @@ defmodule BowlingTest do @tag :pending test "cannot roll if game already has ten frames" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] game = roll_reduce(game, rolls) assert Bowling.roll(game, 0) == {:error, "Cannot roll after game is over"} end @tag :pending test "bonus rolls for a strike in the last frame must be rolled before score can be calculated" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 10] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10] game = roll_reduce(game, rolls) assert Bowling.score(game) == {:error, "Score cannot be taken until the end of the game"} end @tag :pending test "both bonus rolls for a strike in the last frame must be rolled before score can be calculated" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 10, - 10] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 10] game = roll_reduce(game, rolls) assert Bowling.score(game) == {:error, "Score cannot be taken until the end of the game"} end @tag :pending test "bonus roll for a spare in the last frame must be rolled before score can be calculated" do - game = Bowling.start - rolls = [0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 0, 0, - 7, 3] + game = Bowling.start() + rolls = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 3] game = roll_reduce(game, rolls) assert Bowling.score(game) == {:error, "Score cannot be taken until the end of the game"} end diff --git a/exercises/bowling/example.exs b/exercises/bowling/example.exs index 547cc2d73b..151975bc54 100644 --- a/exercises/bowling/example.exs +++ b/exercises/bowling/example.exs @@ -1,5 +1,5 @@ defmodule BowlingGame do - defstruct scores: List.duplicate([0,0], 12), + defstruct scores: List.duplicate([0, 0], 12), current_frame: 1, roll_in_frame: 1 end @@ -19,11 +19,14 @@ defmodule Bowling do def roll(game, score) do updates = update_score(game.roll_in_frame, game, score) + cond do too_many_frames?(updates) -> {:error, "Cannot roll after game is over"} + valid_updates?(updates) -> updates + true -> {:error, "Pin count exceeds pins on the lane"} end @@ -32,11 +35,13 @@ defmodule Bowling do defp update_score(1, game, score) do current_frame = game.current_frame scores = List.replace_at(game.scores, current_frame - 1, [score, 0]) + cond do score == 10 -> - %{ game | current_frame: current_frame + 1, scores: scores } + %{game | current_frame: current_frame + 1, scores: scores} + true -> - %{ game | roll_in_frame: 2, scores: scores } + %{game | roll_in_frame: 2, scores: scores} end end @@ -46,20 +51,21 @@ defmodule Bowling do old_frame_values = Enum.at(old_scores, current_frame - 1) new_frame_values = List.replace_at(old_frame_values, 1, score) new_scores = List.replace_at(old_scores, current_frame - 1, new_frame_values) - %{ game | scores: new_scores, roll_in_frame: 1, - current_frame: current_frame + 1 } + %{game | scores: new_scores, roll_in_frame: 1, current_frame: current_frame + 1} end defp valid_updates?(updates) do - Enum.all?(updates.scores, fn(frame) -> Enum.sum(frame) <= 10 end) + Enum.all?(updates.scores, fn frame -> Enum.sum(frame) <= 10 end) end def score(game) do cond do game.current_frame < 10 -> {:error, "Score cannot be taken until the end of the game"} + bonus_roll_remaining?(game) -> {:error, "Score cannot be taken until the end of the game"} + true -> parse_scores(game.scores) end @@ -67,16 +73,20 @@ defmodule Bowling do defp bonus_roll_remaining?(game) do final_frame = Enum.at(game.scores, 9) + cond do strike?(final_frame) -> cond do strike?(Enum.at(game.scores, 10)) -> game.current_frame == 12 && game.roll_in_frame == 1 + true -> game.current_frame < 12 end + spare?(final_frame) -> game.current_frame == 11 && game.roll_in_frame == 1 + true -> false end @@ -84,6 +94,7 @@ defmodule Bowling do defp too_many_frames?(game) do final_frame = Enum.at(game.scores, 9) + unless strike?(final_frame) || spare?(final_frame) do game.current_frame == 11 && game.roll_in_frame == 2 end @@ -92,18 +103,21 @@ defmodule Bowling do defp parse_scores(scores) do scores |> score_frames - |> Enum.sum + |> Enum.sum() end defp score_frames(scores) do - Enum.map((0..9), fn(idx) -> + Enum.map(0..9, fn idx -> current_frame = Enum.at(scores, idx) - next_frame = Enum.at(scores, idx + 1, [0,0]) + next_frame = Enum.at(scores, idx + 1, [0, 0]) + cond do strike?(current_frame) -> strike(current_frame, next_frame, scores, idx) + spare?(current_frame) -> 10 + hd(next_frame) + true -> Enum.sum(current_frame) end @@ -119,7 +133,7 @@ defmodule Bowling do Enum.sum(current_frame) + Enum.sum(next_frame) + (Enum.at(scores, idx + 2, [0, 0]) |> Enum.at(0)) else - Enum.sum(Enum.at(scores, idx)) + Enum.sum(Enum.at(scores, idx + 1, [0,0])) + Enum.sum(Enum.at(scores, idx)) + Enum.sum(Enum.at(scores, idx + 1, [0, 0])) end end diff --git a/exercises/bracket-push/bracket_push.exs b/exercises/bracket-push/bracket_push.exs index 0f8695bb72..90d9c141a5 100644 --- a/exercises/bracket-push/bracket_push.exs +++ b/exercises/bracket-push/bracket_push.exs @@ -2,8 +2,7 @@ defmodule BracketPush do @doc """ Checks that all the brackets and braces in the string are matched correctly, and nested correctly """ - @spec check_brackets(String.t) :: boolean + @spec check_brackets(String.t()) :: boolean def check_brackets(str) do - end end diff --git a/exercises/bracket-push/bracket_push_test.exs b/exercises/bracket-push/bracket_push_test.exs index a43e2b0109..39beffa528 100644 --- a/exercises/bracket-push/bracket_push_test.exs +++ b/exercises/bracket-push/bracket_push_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("bracket_push.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule BracketPushTest do use ExUnit.Case @@ -75,6 +75,8 @@ defmodule BracketPushTest do @tag :pending test "complex latex expression" do - assert BracketPush.check_brackets("\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \\end{array}\\right)") + assert BracketPush.check_brackets( + "\\left(\\begin{array}{cc} \\frac{1}{3} & x\\\\ \\mathrm{e}^{x} &... x^2 \\end{array}\\right)" + ) end end diff --git a/exercises/bracket-push/example.exs b/exercises/bracket-push/example.exs index aa97aca399..edc3209287 100644 --- a/exercises/bracket-push/example.exs +++ b/exercises/bracket-push/example.exs @@ -8,26 +8,31 @@ defmodule BracketPush do @doc """ Check that all the brackets and braces in the string are matched correctly, and nested correctly """ - @spec check_brackets(String.t) :: boolean + @spec check_brackets(String.t()) :: boolean def check_brackets(str) do str |> String.replace(~r/[^\{\}\[\]\(\)]/, "") - |> String.codepoints + |> String.codepoints() |> check([]) end defp check([], []), do: true defp check([], _), do: false - defp check([h|t], acc) do + + defp check([h | t], acc) do cond do Map.has_key?(@brackets, h) -> check(t, [Map.get(@brackets, h) | acc]) + Enum.empty?(acc) and !Map.has_key?(@brackets, h) -> false + h != hd(acc) -> false + h == hd(acc) -> check(t, tl(acc)) + true -> true end diff --git a/exercises/change/change.exs b/exercises/change/change.exs index 10953a7887..51de714bdd 100644 --- a/exercises/change/change.exs +++ b/exercises/change/change.exs @@ -15,8 +15,7 @@ defmodule Change do """ - @spec generate(list, integer) :: {:ok, list} | {:error, String.t} + @spec generate(list, integer) :: {:ok, list} | {:error, String.t()} def generate(coins, target) do - end end diff --git a/exercises/change/change_test.exs b/exercises/change/change_test.exs index c13cce2d81..111fee17a4 100644 --- a/exercises/change/change_test.exs +++ b/exercises/change/change_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("change.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule ChangeTest do use ExUnit.Case diff --git a/exercises/change/example.exs b/exercises/change/example.exs index 758b4bfebf..e09d3b88b0 100644 --- a/exercises/change/example.exs +++ b/exercises/change/example.exs @@ -15,7 +15,7 @@ defmodule Change do """ - @spec generate(list, integer) :: {:ok, list} | {:error, String.t} + @spec generate(list, integer) :: {:ok, list} | {:error, String.t()} def generate(coins, target) do coins |> Enum.sort(&>/2) |> generate(target, [], {:error, "cannot change"}) end @@ -23,15 +23,19 @@ defmodule Change do defp generate(_, _, current, {:ok, best}) when length(current) >= length(best) do {:ok, best} end + defp generate(_, 0, current, _) do {:ok, current} end + defp generate([], _, _, best) do best end + defp generate([coin | coins], target, current, best) when coin > target do generate(coins, target, current, best) end + defp generate([coin | coins], target, current, best) do first_try = generate([coin | coins], target - coin, [coin | current], best) generate(coins, target, current, first_try) diff --git a/exercises/clock/clock_test.exs b/exercises/clock/clock_test.exs index 41183ca342..ec8720e382 100644 --- a/exercises/clock/clock_test.exs +++ b/exercises/clock/clock_test.exs @@ -2,24 +2,24 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("clock.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule ClockTest do use ExUnit.Case - #@tag :pending + # @tag :pending test "to_string" do try do to_string(%Clock{}) rescue Protocol.UndefinedError -> refute(true, """ - Can't convert Clock to string. - Hint: implement the String.Chars protocol for Clock. - http://elixir-lang.org/getting-started/protocols.html - http://elixir-lang.org/docs/stable/elixir/String.Chars.html - """) + Can't convert Clock to string. + Hint: implement the String.Chars protocol for Clock. + http://elixir-lang.org/getting-started/protocols.html + http://elixir-lang.org/docs/stable/elixir/String.Chars.html + """) end end diff --git a/exercises/clock/example.exs b/exercises/clock/example.exs index e59b578087..4cfdc70148 100644 --- a/exercises/clock/example.exs +++ b/exercises/clock/example.exs @@ -9,7 +9,7 @@ defmodule Clock do iex> Clock.new(8, 9) |> to_string "08:09" """ - @spec new(integer, integer) :: Clock.t + @spec new(integer, integer) :: Clock.t() def new(hour, minute) do rollover(%Clock{hour: hour, minute: minute}) end @@ -20,7 +20,7 @@ defmodule Clock do iex> Clock.new(10, 0) |> Clock.add(3) |> to_string "10:03" """ - @spec add(Clock.t, integer) :: Clock.t + @spec add(Clock.t(), integer) :: Clock.t() def add(%Clock{hour: hour, minute: minute}, add_minute) do new(hour, minute + add_minute) end @@ -38,9 +38,11 @@ defmodule Clock do defp roll_minute(minute) when minute < 0 do {div(minute, 60) - 1, 60 + rem(minute, 60)} end + defp roll_minute(minute) when minute >= 60 do {div(minute, 60), rem(minute, 60)} end + defp roll_minute(minute), do: {0, minute} defimpl String.Chars, for: Clock do @@ -49,7 +51,7 @@ defmodule Clock do end defp format(number) do - number |> Integer.to_string |> String.pad_leading(2, "0") + number |> Integer.to_string() |> String.pad_leading(2, "0") end end end diff --git a/exercises/collatz-conjecture/collatz_conjecture.exs b/exercises/collatz-conjecture/collatz_conjecture.exs index 7438776375..6f8bab785d 100644 --- a/exercises/collatz-conjecture/collatz_conjecture.exs +++ b/exercises/collatz-conjecture/collatz_conjecture.exs @@ -1,5 +1,4 @@ defmodule CollatzConjecture do - @doc """ calc/1 takes an integer and returns the number of steps required to get the number to 1 when following the rules: diff --git a/exercises/collatz-conjecture/collatz_conjecture_test.exs b/exercises/collatz-conjecture/collatz_conjecture_test.exs index 28cc79a780..91aa45512f 100644 --- a/exercises/collatz-conjecture/collatz_conjecture_test.exs +++ b/exercises/collatz-conjecture/collatz_conjecture_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("collatz_conjecture.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule CollatzConjectureTest do use ExUnit.Case @@ -29,7 +29,7 @@ defmodule CollatzConjectureTest do @tag :pending test "Large number of even and odd steps" do - assert CollatzConjecture.calc(1000000) == 152 + assert CollatzConjecture.calc(1_000_000) == 152 end @tag :pending diff --git a/exercises/collatz-conjecture/example.exs b/exercises/collatz-conjecture/example.exs index b0956d93b8..d65206c6ce 100644 --- a/exercises/collatz-conjecture/example.exs +++ b/exercises/collatz-conjecture/example.exs @@ -1,5 +1,4 @@ defmodule CollatzConjecture do - @doc """ calc/1 takes number (> 1), and returns the number of steps required to get to 1 when following the rules: if n is odd, multiply with 3 and add 1. if n is even, divide by 2 @@ -10,6 +9,7 @@ defmodule CollatzConjecture do end defp calc(1, steps), do: steps + defp calc(number, steps) when rem(number, 2) == 0 do calc(div(number, 2), steps + 1) end diff --git a/exercises/connect/connect.exs b/exercises/connect/connect.exs index a22a26699c..0819d8cb99 100644 --- a/exercises/connect/connect.exs +++ b/exercises/connect/connect.exs @@ -4,8 +4,7 @@ defmodule Connect do using "O" as the white player and "X" as the black player """ - @spec result_for([String.t]) :: :none | :black | :white + @spec result_for([String.t()]) :: :none | :black | :white def result_for(board) do - end end diff --git a/exercises/connect/connect_test.exs b/exercises/connect/connect_test.exs index f9bdaf2182..ed1763983e 100644 --- a/exercises/connect/connect_test.exs +++ b/exercises/connect/connect_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("connect.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule ConnectTest do use ExUnit.Case @@ -14,13 +14,15 @@ defmodule ConnectTest do # @tag :pending test "empty board has no winner" do - board = remove_spaces [ - ". . . . .", - " . . . . .", - " . . . . .", - " . . . . .", - " . . . . ." - ] + board = + remove_spaces([ + ". . . . .", + " . . . . .", + " . . . . .", + " . . . . .", + " . . . . ." + ]) + assert Connect.result_for(board) == :none end @@ -38,37 +40,43 @@ defmodule ConnectTest do @tag :pending test "convulted path" do - board = remove_spaces [ - ". X X . .", - " X . X . X", - " . X . X .", - " . X X . .", - " O O O O O" - ] + board = + remove_spaces([ + ". X X . .", + " X . X . X", + " . X . X .", + " . X X . .", + " O O O O O" + ]) + assert Connect.result_for(board) == :black end @tag :pending test "rectangle, black wins" do - board = remove_spaces [ - ". O . .", - " O X X X", - " O X O .", - " X X O X", - " . O X ." - ] + board = + remove_spaces([ + ". O . .", + " O X X X", + " O X O .", + " X X O X", + " . O X ." + ]) + assert Connect.result_for(board) == :black end @tag :pending test "rectangle, white wins" do - board = remove_spaces [ - ". O . .", - " O X X X", - " O O O .", - " X X O X", - " . O X ." - ] + board = + remove_spaces([ + ". O . .", + " O X X X", + " O O O .", + " X X O X", + " . O X ." + ]) + assert Connect.result_for(board) == :white end @@ -85,6 +93,7 @@ defmodule ConnectTest do "OOOOOOOXO", "XXXXXXXXO" ] + assert Connect.result_for(board) == :black end @@ -101,6 +110,7 @@ defmodule ConnectTest do "OOOOOOOXO", "XXXXXXXXO" ] + assert Connect.result_for(board) == :none end end diff --git a/exercises/connect/example.exs b/exercises/connect/example.exs index 75aa7638f6..08b00a89aa 100644 --- a/exercises/connect/example.exs +++ b/exercises/connect/example.exs @@ -4,7 +4,7 @@ defmodule Connect do using "O" as the white player and "X" as the black player """ - @spec result_for([String.t]) :: :none | :black | :white + @spec result_for([String.t()]) :: :none | :black | :white def result_for(board) do cond do black_wins?(board) -> :black @@ -15,35 +15,37 @@ defmodule Connect do defp black_wins?(board) do board - |> Enum.with_index + |> Enum.with_index() |> Enum.any?(fn {row, index} -> String.first(row) == "X" && black_wins?(board, [{index, 0}]) end) end - defp black_wins?(board, [{_, y} | _ ]) when y + 1 == byte_size(hd board), do: true - defp black_wins?(board, history = [last_loc | _ ]) do + defp black_wins?(board, [{_, y} | _]) when y + 1 == byte_size(hd(board)), do: true + + defp black_wins?(board, history = [last_loc | _]) do last_loc |> locs_next_to(history) - |> Enum.filter(&( get_loc(board, &1) == "X" )) + |> Enum.filter(&(get_loc(board, &1) == "X")) |> Enum.any?(&black_wins?(board, [&1 | history])) end defp white_wins?(board) do board |> hd - |> String.graphemes - |> Enum.with_index + |> String.graphemes() + |> Enum.with_index() |> Enum.any?(fn {spot, index} -> spot == "O" && white_wins?(board, [{0, index}]) end) end - defp white_wins?(board, [{x, _} | _ ]) when x + 1 == length(board), do: true - defp white_wins?(board, history = [last_loc | _ ]) do + defp white_wins?(board, [{x, _} | _]) when x + 1 == length(board), do: true + + defp white_wins?(board, history = [last_loc | _]) do last_loc |> locs_next_to(history) - |> Enum.filter(&( get_loc(board, &1) == "O" )) + |> Enum.filter(&(get_loc(board, &1) == "O")) |> Enum.any?(&white_wins?(board, [&1 | history])) end diff --git a/exercises/crypto-square/crypto_square.exs b/exercises/crypto-square/crypto_square.exs index 41bc71c3c4..9a56b16aa9 100644 --- a/exercises/crypto-square/crypto_square.exs +++ b/exercises/crypto-square/crypto_square.exs @@ -6,8 +6,7 @@ defmodule CryptoSquare do iex> CryptoSquare.encode("abcd") "ac bd" """ - @spec encode(String.t) :: String.t + @spec encode(String.t()) :: String.t() def encode(str) do - end end diff --git a/exercises/crypto-square/crypto_square_test.exs b/exercises/crypto-square/crypto_square_test.exs index 83a1ef2e09..fd032075b9 100644 --- a/exercises/crypto-square/crypto_square_test.exs +++ b/exercises/crypto-square/crypto_square_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("crypto_square.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule CryptoSquareTest do use ExUnit.Case diff --git a/exercises/crypto-square/example.exs b/exercises/crypto-square/example.exs index 9dfc0d5207..19d2a9f0c6 100644 --- a/exercises/crypto-square/example.exs +++ b/exercises/crypto-square/example.exs @@ -6,23 +6,24 @@ defmodule CryptoSquare do iex> CryptoSquare.encode("abcd") "ac bd" """ - @spec encode(String.t) :: String.t + @spec encode(String.t()) :: String.t() def encode(""), do: "" + def encode(str) do normalized = normalize_string(str) - section_length = normalized |> byte_size |> :math.sqrt |> Float.ceil |> trunc + section_length = normalized |> byte_size |> :math.sqrt() |> Float.ceil() |> trunc normalized - |> String.graphemes + |> String.graphemes() |> Enum.chunk(section_length, section_length, List.duplicate("", section_length)) - |> List.zip + |> List.zip() |> Enum.map(&Tuple.to_list/1) |> Enum.join(" ") end defp normalize_string(str) do str - |> String.downcase + |> String.downcase() |> String.replace(~r/[^a-z0-9]/, "") end end diff --git a/exercises/custom-set/custom_set.exs b/exercises/custom-set/custom_set.exs index f389d7a44c..0e1b3378ad 100644 --- a/exercises/custom-set/custom_set.exs +++ b/exercises/custom-set/custom_set.exs @@ -1,7 +1,7 @@ defmodule CustomSet do @opaque t :: %__MODULE__{map: map} - @spec new(Enum.t) :: t + @spec new(Enum.t()) :: t def new(enumerable) do end diff --git a/exercises/custom-set/custom_set_test.exs b/exercises/custom-set/custom_set_test.exs index ac74dfb61a..dd5c28bae3 100644 --- a/exercises/custom-set/custom_set_test.exs +++ b/exercises/custom-set/custom_set_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("custom_set.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule CustomSetTest do use ExUnit.Case diff --git a/exercises/custom-set/example.exs b/exercises/custom-set/example.exs index 72013b5cd0..5afc13f6f1 100644 --- a/exercises/custom-set/example.exs +++ b/exercises/custom-set/example.exs @@ -1,16 +1,16 @@ defmodule CustomSet do - defstruct map: Map.new + defstruct map: Map.new() @opaque t :: %__MODULE__{map: map} - @spec new(Enum.t) :: t + @spec new(Enum.t()) :: t def new(enumerable) do - %CustomSet{map: Map.new(enumerable, fn (x) -> {x, true} end)} + %CustomSet{map: Map.new(enumerable, fn x -> {x, true} end)} end @spec empty?(t) :: boolean def empty?(%CustomSet{map: map}) do - Map.keys(map) |> Enum.empty? + Map.keys(map) |> Enum.empty?() end @spec contains?(t, any) :: boolean @@ -28,6 +28,7 @@ defmodule CustomSet do end defp do_subset?([], _), do: true + defp do_subset?([key | rest], map2) do if Map.has_key?(map2, key) do do_subset?(rest, map2) diff --git a/exercises/diamond/diamond.exs b/exercises/diamond/diamond.exs index e905bd379b..00bf687be3 100644 --- a/exercises/diamond/diamond.exs +++ b/exercises/diamond/diamond.exs @@ -3,8 +3,7 @@ defmodule Diamond do Given a letter, it prints a diamond starting with 'A', with the supplied letter at the widest point. """ - @spec build_shape(char) :: String.t + @spec build_shape(char) :: String.t() def build_shape(letter) do - end end diff --git a/exercises/diamond/diamond_test.exs b/exercises/diamond/diamond_test.exs index 6c83158052..edd19cc155 100644 --- a/exercises/diamond/diamond_test.exs +++ b/exercises/diamond/diamond_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("diamond.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule DiamondTest do use ExUnit.Case @@ -17,28 +17,30 @@ defmodule DiamondTest do @tag :pending test "letter C" do shape = Diamond.build_shape(?C) + assert shape == """ -\s A \s -\sB B\s - C C -\sB B\s -\s A \s - """ + \s A \s + \sB B\s + C C + \sB B\s + \s A \s + """ end @tag :pending test "letter E" do shape = Diamond.build_shape(?E) + assert shape == """ -\s A \s -\s B B \s -\s C C \s -\sD D\s - E E -\sD D\s -\s C C \s -\s B B \s -\s A \s - """ + \s A \s + \s B B \s + \s C C \s + \sD D\s + E E + \sD D\s + \s C C \s + \s B B \s + \s A \s + """ end end diff --git a/exercises/diamond/example.exs b/exercises/diamond/example.exs index 078efcdacd..098463c405 100644 --- a/exercises/diamond/example.exs +++ b/exercises/diamond/example.exs @@ -3,7 +3,7 @@ defmodule Diamond do Given a letter, it prints a diamond starting with 'A', with the supplied letter at the widest point. """ - @spec build_shape(char) :: String.t + @spec build_shape(char) :: String.t() def build_shape(letter) do pos = letter - 64 size = pos * 2 - 1 @@ -12,15 +12,15 @@ defmodule Diamond do end defp build_half_diamond(rows, row_size) do - Enum.reduce(0..rows - 1, [], fn x, acc -> - List.duplicate("\s", row_size) - |> List.update_at(rows - 1 - x, fn _ -> <<65 + x>> end) - |> Enum.reverse - |> List.update_at(rows - 1 - x, fn _ -> <<65 + x>> end) - |> List.insert_at(row_size + 1, "\n") - |> List.duplicate(1) - |> Enum.concat(acc) + Enum.reduce(0..(rows - 1), [], fn x, acc -> + List.duplicate("\s", row_size) + |> List.update_at(rows - 1 - x, fn _ -> <<65 + x>> end) + |> Enum.reverse() + |> List.update_at(rows - 1 - x, fn _ -> <<65 + x>> end) + |> List.insert_at(row_size + 1, "\n") + |> List.duplicate(1) + |> Enum.concat(acc) end) - |> Enum.reverse + |> Enum.reverse() end end diff --git a/exercises/difference-of-squares/difference_of_squares.exs b/exercises/difference-of-squares/difference_of_squares.exs index f266a90eb2..9c6b20e582 100644 --- a/exercises/difference-of-squares/difference_of_squares.exs +++ b/exercises/difference-of-squares/difference_of_squares.exs @@ -8,7 +8,6 @@ defmodule Squares do """ @spec sum_of_squares(pos_integer) :: pos_integer def sum_of_squares(number) do - end @doc """ @@ -16,7 +15,6 @@ defmodule Squares do """ @spec square_of_sums(pos_integer) :: pos_integer def square_of_sums(number) do - end @doc """ @@ -24,7 +22,5 @@ defmodule Squares do """ @spec difference(pos_integer) :: pos_integer def difference(number) do - end - -end \ No newline at end of file +end diff --git a/exercises/difference-of-squares/difference_of_squares_test.exs b/exercises/difference-of-squares/difference_of_squares_test.exs index 9c6e6fec17..4ffa9d015f 100644 --- a/exercises/difference-of-squares/difference_of_squares_test.exs +++ b/exercises/difference-of-squares/difference_of_squares_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("difference_of_squares.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule DifferenceOfSquaresTest do use ExUnit.Case @@ -40,17 +40,16 @@ defmodule DifferenceOfSquaresTest do @tag :pending test "square of sums to 100" do - assert Squares.square_of_sums(100) == 25502500 + assert Squares.square_of_sums(100) == 25_502_500 end @tag :pending test "sum of squares to 100" do - assert Squares.sum_of_squares(100) == 338350 + assert Squares.sum_of_squares(100) == 338_350 end @tag :pending test "difference of sums to 100" do - assert Squares.difference(100) == 25164150 + assert Squares.difference(100) == 25_164_150 end - end diff --git a/exercises/difference-of-squares/example.exs b/exercises/difference-of-squares/example.exs index 1e2dcfae63..0b65a6b1af 100644 --- a/exercises/difference-of-squares/example.exs +++ b/exercises/difference-of-squares/example.exs @@ -8,7 +8,7 @@ defmodule Squares do """ @spec sum_of_squares(pos_integer) :: pos_integer def sum_of_squares(number) do - Enum.reduce(1..number, 0, fn(x, acc) -> acc + (x * x) end) + Enum.reduce(1..number, 0, fn x, acc -> acc + x * x end) end @doc """ @@ -16,7 +16,7 @@ defmodule Squares do """ @spec square_of_sums(pos_integer) :: pos_integer def square_of_sums(number) do - sum_to_number = Enum.reduce(1..number, fn(x, acc) -> x + acc end) + sum_to_number = Enum.reduce(1..number, fn x, acc -> x + acc end) sum_to_number * sum_to_number end @@ -27,5 +27,4 @@ defmodule Squares do def difference(number) do square_of_sums(number) - sum_of_squares(number) end - -end \ No newline at end of file +end diff --git a/exercises/diffie-hellman/diffie_hellman.exs b/exercises/diffie-hellman/diffie_hellman.exs index 316de6bccd..deb3e17850 100644 --- a/exercises/diffie-hellman/diffie_hellman.exs +++ b/exercises/diffie-hellman/diffie_hellman.exs @@ -44,7 +44,8 @@ defmodule DiffieHellman do (prime_g ** private_key) % prime_p """ - @spec generate_public_key(prime_p :: integer, prime_g :: integer, private_key :: integer) :: integer + @spec generate_public_key(prime_p :: integer, prime_g :: integer, private_key :: integer) :: + integer def generate_public_key(prime_p, prime_g, private_key) do end @@ -54,8 +55,11 @@ defmodule DiffieHellman do (public_key_b ** private_key_a) % prime_p """ - @spec generate_shared_secret(prime_p :: integer, public_key_b :: integer, private_key_a :: integer) :: integer + @spec generate_shared_secret( + prime_p :: integer, + public_key_b :: integer, + private_key_a :: integer + ) :: integer def generate_shared_secret(prime_p, public_key_b, private_key_a) do end end - diff --git a/exercises/diffie-hellman/diffie_hellman_test.exs b/exercises/diffie-hellman/diffie_hellman_test.exs index 6400ffb00e..bd5b5ca292 100644 --- a/exercises/diffie-hellman/diffie_hellman_test.exs +++ b/exercises/diffie-hellman/diffie_hellman_test.exs @@ -2,24 +2,25 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("diffie_hellman.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule DiffieHellmanTest do use ExUnit.Case - #@tag :pending + # @tag :pending test "private key should be between 1 and P-1, inclusive" do prime_p = 23 - assert DiffieHellman.generate_private_key(prime_p) in Range.new(1, prime_p-1) + assert DiffieHellman.generate_private_key(prime_p) in Range.new(1, prime_p - 1) end @tag :pending test "private key generator should support very large primes" do - prime_p = 120227323036150778550155526710966921740030662694578947298423549235265759593711587341037426347114541533006628856300552706996143592240453345642869233562886752930249953227657883929905072620233073626594386072962776144691433658814261874113232461749035425712805067202910389407991986070558964461330091797026762932543 + prime_p = + 120_227_323_036_150_778_550_155_526_710_966_921_740_030_662_694_578_947_298_423_549_235_265_759_593_711_587_341_037_426_347_114_541_533_006_628_856_300_552_706_996_143_592_240_453_345_642_869_233_562_886_752_930_249_953_227_657_883_929_905_072_620_233_073_626_594_386_072_962_776_144_691_433_658_814_261_874_113_232_461_749_035_425_712_805_067_202_910_389_407_991_986_070_558_964_461_330_091_797_026_762_932_543 - assert DiffieHellman.generate_private_key(prime_p) in Range.new(1, prime_p-1) + assert DiffieHellman.generate_private_key(prime_p) in Range.new(1, prime_p - 1) end @tag :pending @@ -30,10 +31,12 @@ defmodule DiffieHellmanTest do # the same numbers over an over, so this may fail, but the RNG should be good enough # that 100 generated keys between 1 and 22 ought to be at least half unique. - unique_key_count = Stream.repeatedly(fn -> DiffieHellman.generate_private_key(prime_p) end) - |> Enum.take(100) - |> Enum.uniq - |> length + unique_key_count = + Stream.repeatedly(fn -> DiffieHellman.generate_private_key(prime_p) end) + |> Enum.take(100) + |> Enum.uniq() + |> length + min_expected_unique_keys = div(prime_p, 2) assert unique_key_count > min_expected_unique_keys @@ -51,10 +54,16 @@ defmodule DiffieHellmanTest do @tag :pending test "public key generator should support very large primes" do - prime_p = 120227323036150778550155526710966921740030662694578947298423549235265759593711587341037426347114541533006628856300552706996143592240453345642869233562886752930249953227657883929905072620233073626594386072962776144691433658814261874113232461749035425712805067202910389407991986070558964461330091797026762932543 - prime_g = 75205441154357919442925546169208711235485855904969178206313309299205868312399046149367516336607966149689640419216591714331722664409474612463910928128055994157922930443733535659848264364106037925315974095321112757711756912144137705613776063541350548911512715512539186192176020596861210448363099541947258202188 - private_key = 8675309 - expected_public_key = 81945102766205597052444239927191366879878802281637258134656723311532689587789695879960502348293388789700383121890410484395608064685866057972603193444399431765316092443741213175747052166212523610645396217140238838864033970876203333493173215068467082830013531737232331628864212666452277691016389511356912249174 + prime_p = + 120_227_323_036_150_778_550_155_526_710_966_921_740_030_662_694_578_947_298_423_549_235_265_759_593_711_587_341_037_426_347_114_541_533_006_628_856_300_552_706_996_143_592_240_453_345_642_869_233_562_886_752_930_249_953_227_657_883_929_905_072_620_233_073_626_594_386_072_962_776_144_691_433_658_814_261_874_113_232_461_749_035_425_712_805_067_202_910_389_407_991_986_070_558_964_461_330_091_797_026_762_932_543 + + prime_g = + 75_205_441_154_357_919_442_925_546_169_208_711_235_485_855_904_969_178_206_313_309_299_205_868_312_399_046_149_367_516_336_607_966_149_689_640_419_216_591_714_331_722_664_409_474_612_463_910_928_128_055_994_157_922_930_443_733_535_659_848_264_364_106_037_925_315_974_095_321_112_757_711_756_912_144_137_705_613_776_063_541_350_548_911_512_715_512_539_186_192_176_020_596_861_210_448_363_099_541_947_258_202_188 + + private_key = 8_675_309 + + expected_public_key = + 81_945_102_766_205_597_052_444_239_927_191_366_879_878_802_281_637_258_134_656_723_311_532_689_587_789_695_879_960_502_348_293_388_789_700_383_121_890_410_484_395_608_064_685_866_057_972_603_193_444_399_431_765_316_092_443_741_213_175_747_052_166_212_523_610_645_396_217_140_238_838_864_033_970_876_203_333_493_173_215_068_467_082_830_013_531_737_232_331_628_864_212_666_452_277_691_016_389_511_356_912_249_174 assert DiffieHellman.generate_public_key(prime_p, prime_g, private_key) == expected_public_key end @@ -66,17 +75,26 @@ defmodule DiffieHellmanTest do alice_private_key = 6 expected_shared_secret = 2 - assert DiffieHellman.generate_shared_secret(prime_p, bob_public_key, alice_private_key) == expected_shared_secret + assert DiffieHellman.generate_shared_secret(prime_p, bob_public_key, alice_private_key) == + expected_shared_secret end @tag :pending test "shared secret correctly calculated when using large primes" do - prime_p = 120227323036150778550155526710966921740030662694578947298423549235265759593711587341037426347114541533006628856300552706996143592240453345642869233562886752930249953227657883929905072620233073626594386072962776144691433658814261874113232461749035425712805067202910389407991986070558964461330091797026762932543 - bob_public_key = 75205441154357919442925546169208711235485855904969178206313309299205868312399046149367516336607966149689640419216591714331722664409474612463910928128055994157922930443733535659848264364106037925315974095321112757711756912144137705613776063541350548911512715512539186192176020596861210448363099541947258202188 - alice_private_key = 2483479393625932939911081304356888505153797135447327501792696199190469015215177630758617902200417377685436170904594686456961202706692908603181062371925882 - expected_shared_secret = 70900735223964890815905879227737819348808518698920446491346508980461201746567735331455825644429877946556431095820785835497384849778344216981228226252639932672153547963980483673419756271345828771971984887453014488572245819864454136618980914729839523581263886740821363010486083940557620831348661126601106717071 + prime_p = + 120_227_323_036_150_778_550_155_526_710_966_921_740_030_662_694_578_947_298_423_549_235_265_759_593_711_587_341_037_426_347_114_541_533_006_628_856_300_552_706_996_143_592_240_453_345_642_869_233_562_886_752_930_249_953_227_657_883_929_905_072_620_233_073_626_594_386_072_962_776_144_691_433_658_814_261_874_113_232_461_749_035_425_712_805_067_202_910_389_407_991_986_070_558_964_461_330_091_797_026_762_932_543 + + bob_public_key = + 75_205_441_154_357_919_442_925_546_169_208_711_235_485_855_904_969_178_206_313_309_299_205_868_312_399_046_149_367_516_336_607_966_149_689_640_419_216_591_714_331_722_664_409_474_612_463_910_928_128_055_994_157_922_930_443_733_535_659_848_264_364_106_037_925_315_974_095_321_112_757_711_756_912_144_137_705_613_776_063_541_350_548_911_512_715_512_539_186_192_176_020_596_861_210_448_363_099_541_947_258_202_188 - assert DiffieHellman.generate_shared_secret(prime_p, bob_public_key, alice_private_key) == expected_shared_secret + alice_private_key = + 2_483_479_393_625_932_939_911_081_304_356_888_505_153_797_135_447_327_501_792_696_199_190_469_015_215_177_630_758_617_902_200_417_377_685_436_170_904_594_686_456_961_202_706_692_908_603_181_062_371_925_882 + + expected_shared_secret = + 70_900_735_223_964_890_815_905_879_227_737_819_348_808_518_698_920_446_491_346_508_980_461_201_746_567_735_331_455_825_644_429_877_946_556_431_095_820_785_835_497_384_849_778_344_216_981_228_226_252_639_932_672_153_547_963_980_483_673_419_756_271_345_828_771_971_984_887_453_014_488_572_245_819_864_454_136_618_980_914_729_839_523_581_263_886_740_821_363_010_486_083_940_557_620_831_348_661_126_601_106_717_071 + + assert DiffieHellman.generate_shared_secret(prime_p, bob_public_key, alice_private_key) == + expected_shared_secret end @tag :pending @@ -90,10 +108,12 @@ defmodule DiffieHellmanTest do alice_public_key = DiffieHellman.generate_public_key(prime_p, prime_g, alice_private_key) bob_public_key = DiffieHellman.generate_public_key(prime_p, prime_g, bob_private_key) - alice_shared_secret = DiffieHellman.generate_shared_secret(prime_p, bob_public_key, alice_private_key) - bob_shared_secret = DiffieHellman.generate_shared_secret(prime_p, alice_public_key, bob_private_key) + alice_shared_secret = + DiffieHellman.generate_shared_secret(prime_p, bob_public_key, alice_private_key) + + bob_shared_secret = + DiffieHellman.generate_shared_secret(prime_p, alice_public_key, bob_private_key) assert alice_shared_secret == bob_shared_secret end end - diff --git a/exercises/diffie-hellman/example.exs b/exercises/diffie-hellman/example.exs index 633f265695..afd1e2fea7 100644 --- a/exercises/diffie-hellman/example.exs +++ b/exercises/diffie-hellman/example.exs @@ -36,7 +36,7 @@ defmodule DiffieHellman do """ @spec generate_private_key(prime_p :: integer) :: integer def generate_private_key(prime_p) do - 1 |> Range.new(prime_p - 1) |> Enum.random + 1 |> Range.new(prime_p - 1) |> Enum.random() end @doc """ @@ -45,9 +45,10 @@ defmodule DiffieHellman do (prime_g ** private_key) % prime_p """ - @spec generate_public_key(prime_p :: integer, prime_g :: integer, private_key :: integer) :: integer + @spec generate_public_key(prime_p :: integer, prime_g :: integer, private_key :: integer) :: + integer def generate_public_key(prime_p, prime_g, private_key) do - :crypto.mod_pow(prime_g, private_key, prime_p) |> :binary.decode_unsigned + :crypto.mod_pow(prime_g, private_key, prime_p) |> :binary.decode_unsigned() end @doc """ @@ -56,9 +57,12 @@ defmodule DiffieHellman do (public_key_b ** private_key_a) % prime_p """ - @spec generate_shared_secret(prime_p :: integer, public_key_b :: integer, private_key_a :: integer) :: integer + @spec generate_shared_secret( + prime_p :: integer, + public_key_b :: integer, + private_key_a :: integer + ) :: integer def generate_shared_secret(prime_p, public_key_b, private_key_a) do - :crypto.mod_pow(public_key_b, private_key_a, prime_p) |> :binary.decode_unsigned + :crypto.mod_pow(public_key_b, private_key_a, prime_p) |> :binary.decode_unsigned() end end - diff --git a/exercises/dominoes/dominoes.exs b/exercises/dominoes/dominoes.exs index 7e5b7444a8..2cb4029636 100644 --- a/exercises/dominoes/dominoes.exs +++ b/exercises/dominoes/dominoes.exs @@ -1,5 +1,4 @@ defmodule Dominoes do - @type domino :: {1..6, 1..6} @doc """ diff --git a/exercises/dominoes/dominoes_test.exs b/exercises/dominoes/dominoes_test.exs index acd9a1b4c6..414c7ccbe5 100644 --- a/exercises/dominoes/dominoes_test.exs +++ b/exercises/dominoes/dominoes_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("dominoes.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule DominoesTest do use ExUnit.Case @@ -49,7 +49,8 @@ defmodule DominoesTest do @tag :pending test "need backtrack" do - assert Dominoes.chain?([{1, 2}, {2, 3}, {3, 1}, {2, 4}, {2, 4}]) == true # a variation in which we have to turn but no duplicates + # a variation in which we have to turn but no duplicates + assert Dominoes.chain?([{1, 2}, {2, 3}, {3, 1}, {2, 4}, {2, 4}]) == true end @tag :pending @@ -59,9 +60,18 @@ defmodule DominoesTest do @tag :pending test "nine elements" do - assert Dominoes.chain?([{1, 2}, {5, 3}, {3, 1}, {1, 2}, {2, 4}, {1, 6}, {2, 3}, {3, 4}, {5, 6}]) == true - end - + assert Dominoes.chain?([ + {1, 2}, + {5, 3}, + {3, 1}, + {1, 2}, + {2, 4}, + {1, 6}, + {2, 3}, + {3, 4}, + {5, 6} + ]) == true + end @tag :pending test "disconnected - simple" do diff --git a/exercises/dominoes/example.exs b/exercises/dominoes/example.exs index 769d3f4159..24249af0bb 100644 --- a/exercises/dominoes/example.exs +++ b/exercises/dominoes/example.exs @@ -1,5 +1,4 @@ defmodule Dominoes do - @type domino :: {1..6, 1..6} @doc """ @@ -13,7 +12,9 @@ defmodule Dominoes do def chain?(dominoes), do: [] !== chains(dominoes) def chains([first | rest]) do - for combi <- permutations(rest), {:ok, result} <- chain(combi, [], first), do: result + for combi <- permutations(rest), + {:ok, result} <- chain(combi, [], first), + do: result end defp chain([], [{a, _} | _] = acc, {_, a} = last), do: [{:ok, acc ++ [last]}] @@ -23,18 +24,21 @@ defmodule Dominoes do chain(rest, acc ++ [next], this) end - defp chain([{c, b} | rest], acc, {_, b} = next) when b != c do + defp chain([{c, b} | rest], acc, {_, b} = next) when b != c do chain(rest, acc ++ [next], {b, c}) end - defp chain([{b, b} = this | rest], acc, {_, b} = next) do + defp chain([{b, b} = this | rest], acc, {_, b} = next) do chain(rest, acc ++ [next], this) end defp chain(_a, _b, _c), do: [{:error, :no_followup}] defp permutations([]), do: [[]] + defp permutations(list) do - for h <- list, t <- permutations(list -- [h]), do: [h | t] + for h <- list, + t <- permutations(list -- [h]), + do: [h | t] end end diff --git a/exercises/dot-dsl/dot.exs b/exercises/dot-dsl/dot.exs index 749143448d..6a79fca27d 100644 --- a/exercises/dot-dsl/dot.exs +++ b/exercises/dot-dsl/dot.exs @@ -4,6 +4,5 @@ end defmodule Dot do defmacro graph(ast) do - end end diff --git a/exercises/dot-dsl/dot_dsl_test.exs b/exercises/dot-dsl/dot_dsl_test.exs index 7bb8036868..12f6b8721a 100644 --- a/exercises/dot-dsl/dot_dsl_test.exs +++ b/exercises/dot-dsl/dot_dsl_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("dot.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule DotTest do use ExUnit.Case @@ -15,6 +15,7 @@ defmodule DotTest do # Inspired by (read: clone of) Support.CompileHelpers.delay_compile in Ecto. defmacrop exprt(ast) do escaped = Macro.escape(ast) + quote do Code.eval_quoted(unquote(escaped), [], __ENV__) |> elem(0) end @@ -22,144 +23,192 @@ defmodule DotTest do # @tag :pending test "empty graph" do - assert %Graph{} == exprt(Dot.graph do end) + assert %Graph{} == + exprt( + Dot.graph do + end + ) end @tag :pending test "graph with one node" do - assert %Graph{nodes: [{:a, []}]} == exprt(Dot.graph do a end) + assert %Graph{nodes: [{:a, []}]} == + exprt( + Dot.graph do + a + end + ) end @tag :pending test "graph with one node with keywords" do - assert %Graph{nodes: [{:a, [color: :green]}]} == exprt(Dot.graph do a [color: :green] end) + assert %Graph{nodes: [{:a, [color: :green]}]} == + exprt( + Dot.graph do + a(color: :green) + end + ) end @tag :pending test "graph with one edge" do - assert %Graph{edges: [{:a, :b, []}]} == exprt(Dot.graph do a -- b end) + assert %Graph{edges: [{:a, :b, []}]} == + exprt( + Dot.graph do + a -- b + end + ) end @tag :pending test "graph with just attribute" do - assert %Graph{attrs: [foo: 1]} == exprt(Dot.graph do graph [foo: 1] end) + assert %Graph{attrs: [foo: 1]} == + exprt( + Dot.graph do + graph(foo: 1) + end + ) end @tag :pending test "graph with attributes" do assert %Graph{ - attrs: [bar: true, foo: 1, title: "Testing Attrs"], - nodes: [{:a, [color: :green]}, - {:b, [label: "Beta!"]}, - {:c, []}], - edges: [{:a, :b, [color: :blue]}, - {:b, :c, []}] - } == exprt(Dot.graph do - graph [foo: 1] - graph [title: "Testing Attrs"] - graph [] - a [color: :green] - c [] - b [label: "Beta!"] - b -- c [] - a -- b [color: :blue] - graph [bar: true] - end) + attrs: [bar: true, foo: 1, title: "Testing Attrs"], + nodes: [{:a, [color: :green]}, {:b, [label: "Beta!"]}, {:c, []}], + edges: [{:a, :b, [color: :blue]}, {:b, :c, []}] + } == + exprt( + Dot.graph do + graph(foo: 1) + graph(title: "Testing Attrs") + graph([]) + a(color: :green) + c([]) + b(label: "Beta!") + b -- c([]) + a -- b(color: :blue) + graph(bar: true) + end + ) end @tag :pending test "keywords stuck to graph without space" do assert_raise ArgumentError, fn -> - exprt(Dot.graph do - graph[title: "Bad"] - end) + exprt( + Dot.graph do + graph[[title: "Bad"]] + end + ) end end @tag :pending test "keywords stuck to node without space" do assert_raise ArgumentError, fn -> - exprt(Dot.graph do - a[label: "Alpha!"] - end) + exprt( + Dot.graph do + a[[label: "Alpha!"]] + end + ) end end @tag :pending test "keywords stuck to edge without space" do assert_raise ArgumentError, fn -> - exprt(Dot.graph do - a -- b[label: "Bad"] - end) + exprt( + Dot.graph do + a -- b[[label: "Bad"]] + end + ) end end @tag :pending test "invalid statement: int" do assert_raise ArgumentError, fn -> - exprt(Dot.graph do - a - 2 - end) + exprt( + Dot.graph do + a + 2 + end + ) end end @tag :pending test "invalid statement: list" do assert_raise ArgumentError, fn -> - exprt(Dot.graph do - [title: "Testing invalid"] - end) + exprt( + Dot.graph do + [title: "Testing invalid"] + end + ) end end @tag :pending test "invalid statement: qualified atom" do assert_raise ArgumentError, fn -> - exprt(Dot.graph do - Enum.map - end) + exprt( + Dot.graph do + Enum.map() + end + ) end end @tag :pending test "invalid statement: graph with no keywords" do assert_raise ArgumentError, fn -> - exprt(Dot.graph do - Enum.map - end) + exprt( + Dot.graph do + Enum.map() + end + ) end end @tag :pending test "two attribute lists" do assert_raise ArgumentError, fn -> - exprt(Dot.graph do - a [color: green][label: "Alpha!"] - end) |> IO.inspect + exprt( + Dot.graph do + a([color: green][[label: "Alpha!"]]) + end + ) + |> IO.inspect() end end @tag :pending test "non-keyword attribute list" do assert_raise ArgumentError, fn -> - exprt(Dot.graph do - a ["Alpha!", color: green] - end) + exprt( + Dot.graph do + a(["Alpha!", color: green]) + end + ) end end @tag :pending test "int edge" do assert_raise ArgumentError, fn -> - exprt(Dot.graph do - 1 -- b - end) + exprt( + Dot.graph do + 1 -- b + end + ) end + assert_raise ArgumentError, fn -> - exprt(Dot.graph do - a -- 2 - end) + exprt( + Dot.graph do + a -- 2 + end + ) end end end diff --git a/exercises/dot-dsl/example.exs b/exercises/dot-dsl/example.exs index 1c033db18e..2409c3644b 100644 --- a/exercises/dot-dsl/example.exs +++ b/exercises/dot-dsl/example.exs @@ -6,20 +6,24 @@ defmodule Dot do # Normally matching on keywords is a bad idea as keyword lists can have # several orders (i.e. `[a: 1, b: 2]` and `[b: 2, a: 1]`). But in this case # only one keyword is allowed, so it's safe. - defmacro graph([do: ast]) do + defmacro graph(do: ast) do g = do_graph(ast) - Macro.escape( - %Graph{attrs: Enum.sort(g.attrs), - nodes: Enum.sort(g.nodes), - edges: Enum.sort(g.edges)}) + + Macro.escape(%Graph{ + attrs: Enum.sort(g.attrs), + nodes: Enum.sort(g.nodes), + edges: Enum.sort(g.edges) + }) end defp do_graph(nil) do %Graph{} end + defp do_graph({:__block__, _, stmts}) do Enum.reduce(stmts, %Graph{}, &do_stmt/2) end + defp do_graph(stmt) do do_stmt(stmt, %Graph{}) end @@ -31,35 +35,39 @@ defmodule Dot do raise_invalid_stmt(stmt) end end + defp do_stmt({atom, _, nil}, g) when is_atom(atom) and atom != :-- do %{g | nodes: [{atom, []} | g.nodes]} end + defp do_stmt(stmt = {atom, _, [kws]}, g) - when is_atom(atom) and atom != :-- and is_list(kws) do + when is_atom(atom) and atom != :-- and is_list(kws) do if Keyword.keyword?(kws) do %{g | nodes: [{atom, kws} | g.nodes]} else raise_invalid_stmt(stmt) end end + defp do_stmt({:--, _, [{a, _, nil}, {b, _, nil}]}, g) - when is_atom(a) and is_atom(b) do + when is_atom(a) and is_atom(b) do %{g | edges: [{a, b, []} | g.edges]} end + defp do_stmt(stmt = {:--, _, [{a, _, nil}, {b, _, [kws]}]}, g) - when is_atom(a) and is_atom(b) and is_list(kws) do + when is_atom(a) and is_atom(b) and is_list(kws) do if Keyword.keyword?(kws) do %{g | edges: [{a, b, kws} | g.edges]} else raise_invalid_stmt(stmt) end end + defp do_stmt(stmt, _) do raise_invalid_stmt(stmt) end defp raise_invalid_stmt(stmt) do - raise ArgumentError, message: "Invalid statement: #{inspect stmt}" + raise ArgumentError, message: "Invalid statement: #{inspect(stmt)}" end - end diff --git a/exercises/etl/etl.exs b/exercises/etl/etl.exs index 5b6892405c..b83522caaa 100644 --- a/exercises/etl/etl.exs +++ b/exercises/etl/etl.exs @@ -9,6 +9,5 @@ defmodule ETL do """ @spec transform(map) :: map def transform(input) do - end end diff --git a/exercises/etl/etl_test.exs b/exercises/etl/etl_test.exs index 77dd2fd619..8ee2cb97d8 100644 --- a/exercises/etl/etl_test.exs +++ b/exercises/etl/etl_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("etl.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule TransformTest do use ExUnit.Case @@ -27,6 +27,7 @@ defmodule TransformTest do @tag :pending test "more keys" do old = %{1 => ["APPLE", "ARTICHOKE"], 2 => ["BOAT", "BALLERINA"]} + expected = %{ "apple" => 1, "artichoke" => 1, @@ -40,21 +41,41 @@ defmodule TransformTest do @tag :pending test "full dataset" do old = %{ - 1 => ~W(A E I O U L N R S T), - 2 => ~W(D G), - 3 => ~W(B C M P), - 4 => ~W(F H V W Y), - 5 => ~W(K), - 8 => ~W(J X), + 1 => ~W(A E I O U L N R S T), + 2 => ~W(D G), + 3 => ~W(B C M P), + 4 => ~W(F H V W Y), + 5 => ~W(K), + 8 => ~W(J X), 10 => ~W(Q Z) } expected = %{ - "a" => 1, "b" => 3, "c" => 3, "d" => 2, "e" => 1, - "f" => 4, "g" => 2, "h" => 4, "i" => 1, "j" => 8, - "k" => 5, "l" => 1, "m" => 3, "n" => 1, "o" => 1, - "p" => 3, "q" => 10, "r" => 1, "s" => 1, "t" => 1, - "u" => 1, "v" => 4, "w" => 4, "x" => 8, "y" => 4, + "a" => 1, + "b" => 3, + "c" => 3, + "d" => 2, + "e" => 1, + "f" => 4, + "g" => 2, + "h" => 4, + "i" => 1, + "j" => 8, + "k" => 5, + "l" => 1, + "m" => 3, + "n" => 1, + "o" => 1, + "p" => 3, + "q" => 10, + "r" => 1, + "s" => 1, + "t" => 1, + "u" => 1, + "v" => 4, + "w" => 4, + "x" => 8, + "y" => 4, "z" => 10 } diff --git a/exercises/etl/example.exs b/exercises/etl/example.exs index 2786df7772..a91e9ed3a6 100644 --- a/exercises/etl/example.exs +++ b/exercises/etl/example.exs @@ -9,15 +9,15 @@ defmodule ETL do """ def transform(input) do input - |> Map.to_list - |> invert - |> List.flatten - |> Enum.into(%{}) + |> Map.to_list() + |> invert + |> List.flatten() + |> Enum.into(%{}) end defp invert(pairs) do - Enum.map(pairs, fn({key, values}) -> - Enum.map(values, fn(value) -> {String.downcase(value), key} end) + Enum.map(pairs, fn {key, values} -> + Enum.map(values, fn value -> {String.downcase(value), key} end) end) end end diff --git a/exercises/flatten-array/flatten_array.exs b/exercises/flatten-array/flatten_array.exs index 04dbac39f5..28db74829b 100644 --- a/exercises/flatten-array/flatten_array.exs +++ b/exercises/flatten-array/flatten_array.exs @@ -14,6 +14,5 @@ defmodule FlattenArray do @spec flatten(list) :: list def flatten(list) do - end end diff --git a/exercises/flatten-array/flatten_array_test.exs b/exercises/flatten-array/flatten_array_test.exs index add2de1a34..5296fd7a0e 100644 --- a/exercises/flatten-array/flatten_array_test.exs +++ b/exercises/flatten-array/flatten_array_test.exs @@ -2,38 +2,38 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("flatten_array.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule FlattenArrayTest do use ExUnit.Case test "returns original list if there is nothing to flatten" do - assert FlattenArray.flatten([1, 2, 3]) == [1, 2, 3] + assert FlattenArray.flatten([1, 2, 3]) == [1, 2, 3] end @tag :pending test "flattens an empty nested list" do - assert FlattenArray.flatten([[]]) == [] + assert FlattenArray.flatten([[]]) == [] end @tag :pending test "flattens a nested list" do - assert FlattenArray.flatten([1,[2,[3],4],5,[6,[7,8]]]) == [1, 2, 3, 4, 5, 6, 7, 8] + assert FlattenArray.flatten([1, [2, [3], 4], 5, [6, [7, 8]]]) == [1, 2, 3, 4, 5, 6, 7, 8] end @tag :pending test "removes nil from list" do - assert FlattenArray.flatten([1, nil, 2]) == [1, 2] + assert FlattenArray.flatten([1, nil, 2]) == [1, 2] end @tag :pending test "removes nil from a nested list" do - assert FlattenArray.flatten([1, [2, nil, 4], 5]) == [1, 2, 4, 5] + assert FlattenArray.flatten([1, [2, nil, 4], 5]) == [1, 2, 4, 5] end @tag :pending test "returns an empty list if all values in nested list are nil" do - assert FlattenArray.flatten([nil, [nil], [nil, [nil]]]) == [] + assert FlattenArray.flatten([nil, [nil], [nil, [nil]]]) == [] end end diff --git a/exercises/forth/example.exs b/exercises/forth/example.exs index 56bbc31372..45873701b8 100644 --- a/exercises/forth/example.exs +++ b/exercises/forth/example.exs @@ -135,11 +135,11 @@ defmodule Forth do Regex.scan(~r/[\p{L}\p{N}\p{S}\p{P}]+/u, s) |> Stream.map(&hd/1) |> Enum.map(fn t -> - case Integer.parse(t) do - {i, ""} -> i - _ -> t - end - end) + case Integer.parse(t) do + {i, ""} -> i + _ -> t + end + end) end @doc """ diff --git a/exercises/forth/forth.exs b/exercises/forth/forth.exs index ca8ec9173e..e7c22d6ddf 100644 --- a/exercises/forth/forth.exs +++ b/exercises/forth/forth.exs @@ -6,24 +6,21 @@ defmodule Forth do """ @spec new() :: evaluator def new() do - end @doc """ Evaluate an input string, updating the evaluator state. """ - @spec eval(evaluator, String.t) :: evaluator + @spec eval(evaluator, String.t()) :: evaluator def eval(ev, s) do - end @doc """ Return the current stack as a string with the element on top of the stack being the rightmost element in the string. """ - @spec format_stack(evaluator) :: String.t + @spec format_stack(evaluator) :: String.t() def format_stack(ev) do - end defmodule StackUnderflow do @@ -32,13 +29,13 @@ defmodule Forth do end defmodule InvalidWord do - defexception [word: nil] - def message(e), do: "invalid word: #{inspect e.word}" + defexception word: nil + def message(e), do: "invalid word: #{inspect(e.word)}" end defmodule UnknownWord do - defexception [word: nil] - def message(e), do: "unknown word: #{inspect e.word}" + defexception word: nil + def message(e), do: "unknown word: #{inspect(e.word)}" end defmodule DivisionByZero do diff --git a/exercises/forth/forth_test.exs b/exercises/forth/forth_test.exs index 2ed854681c..984419f188 100644 --- a/exercises/forth/forth_test.exs +++ b/exercises/forth/forth_test.exs @@ -2,167 +2,210 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("forth.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule ForthTest do use ExUnit.Case # @tag :pending test "no input, no stack" do - s = Forth.new |> Forth.format_stack + s = Forth.new() |> Forth.format_stack() assert s == "" end @tag :pending test "numbers just get pushed onto the stack" do - s = Forth.new - |> Forth.eval("1 2 3 4 5") - |> Forth.format_stack + s = + Forth.new() + |> Forth.eval("1 2 3 4 5") + |> Forth.format_stack() + assert s == "1 2 3 4 5" end @tag :pending test "non-word characters are separators" do # Note the Ogham Space Mark ( ), this is a spacing character. - s = Forth.new - |> Forth.eval("1\x002\x013\n4\r5 6\t7") - |> Forth.format_stack + s = + Forth.new() + |> Forth.eval("1\x002\x013\n4\r5 6\t7") + |> Forth.format_stack() + assert s == "1 2 3 4 5 6 7" end @tag :pending test "basic arithmetic" do - s = Forth.new - |> Forth.eval("1 2 + 4 -") - |> Forth.format_stack + s = + Forth.new() + |> Forth.eval("1 2 + 4 -") + |> Forth.format_stack() + assert s == "-1" - s = Forth.new - |> Forth.eval("2 4 * 3 /") # integer division - |> Forth.format_stack + # integer division + s = + Forth.new() + |> Forth.eval("2 4 * 3 /") + |> Forth.format_stack() + assert s == "2" end @tag :pending test "division by zero" do assert_raise Forth.DivisionByZero, fn -> - Forth.new |> Forth.eval("4 2 2 - /") + Forth.new() |> Forth.eval("4 2 2 - /") end end @tag :pending test "dup" do - s = Forth.new - |> Forth.eval("1 DUP") - |> Forth.format_stack + s = + Forth.new() + |> Forth.eval("1 DUP") + |> Forth.format_stack() + assert s == "1 1" - s = Forth.new - |> Forth.eval("1 2 Dup") - |> Forth.format_stack + + s = + Forth.new() + |> Forth.eval("1 2 Dup") + |> Forth.format_stack() + assert s == "1 2 2" + assert_raise Forth.StackUnderflow, fn -> - Forth.new |> Forth.eval("dup") + Forth.new() |> Forth.eval("dup") end end @tag :pending test "drop" do - s = Forth.new - |> Forth.eval("1 drop") - |> Forth.format_stack + s = + Forth.new() + |> Forth.eval("1 drop") + |> Forth.format_stack() + assert s == "" - s = Forth.new - |> Forth.eval("1 2 drop") - |> Forth.format_stack + + s = + Forth.new() + |> Forth.eval("1 2 drop") + |> Forth.format_stack() + assert s == "1" + assert_raise Forth.StackUnderflow, fn -> - Forth.new |> Forth.eval("drop") + Forth.new() |> Forth.eval("drop") end end @tag :pending test "swap" do - s = Forth.new - |> Forth.eval("1 2 swap") - |> Forth.format_stack + s = + Forth.new() + |> Forth.eval("1 2 swap") + |> Forth.format_stack() + assert s == "2 1" - s = Forth.new - |> Forth.eval("1 2 3 swap") - |> Forth.format_stack + + s = + Forth.new() + |> Forth.eval("1 2 3 swap") + |> Forth.format_stack() + assert s == "1 3 2" + assert_raise Forth.StackUnderflow, fn -> - Forth.new |> Forth.eval("1 swap") + Forth.new() |> Forth.eval("1 swap") end + assert_raise Forth.StackUnderflow, fn -> - Forth.new |> Forth.eval("swap") + Forth.new() |> Forth.eval("swap") end end @tag :pending test "over" do - s = Forth.new - |> Forth.eval("1 2 over") - |> Forth.format_stack + s = + Forth.new() + |> Forth.eval("1 2 over") + |> Forth.format_stack() + assert s == "1 2 1" - s = Forth.new - |> Forth.eval("1 2 3 over") - |> Forth.format_stack + + s = + Forth.new() + |> Forth.eval("1 2 3 over") + |> Forth.format_stack() + assert s == "1 2 3 2" + assert_raise Forth.StackUnderflow, fn -> - Forth.new |> Forth.eval("1 over") + Forth.new() |> Forth.eval("1 over") end + assert_raise Forth.StackUnderflow, fn -> - Forth.new |> Forth.eval("over") + Forth.new() |> Forth.eval("over") end end @tag :pending test "defining a new word" do - s = Forth.new - |> Forth.eval(": dup-twice dup dup ;") - |> Forth.eval("1 dup-twice") - |> Forth.format_stack + s = + Forth.new() + |> Forth.eval(": dup-twice dup dup ;") + |> Forth.eval("1 dup-twice") + |> Forth.format_stack() + assert s == "1 1 1" end @tag :pending test "redefining an existing word" do - s = Forth.new - |> Forth.eval(": foo dup ;") - |> Forth.eval(": foo dup dup ;") - |> Forth.eval("1 foo") - |> Forth.format_stack + s = + Forth.new() + |> Forth.eval(": foo dup ;") + |> Forth.eval(": foo dup dup ;") + |> Forth.eval("1 foo") + |> Forth.format_stack() + assert s == "1 1 1" end @tag :pending test "redefining an existing built-in word" do - s = Forth.new - |> Forth.eval(": swap dup ;") - |> Forth.eval("1 swap") - |> Forth.format_stack + s = + Forth.new() + |> Forth.eval(": swap dup ;") + |> Forth.eval("1 swap") + |> Forth.format_stack() + assert s == "1 1" end @tag :pending test "defining words with odd characters" do - s = Forth.new - |> Forth.eval(": € 220371 ; €") - |> Forth.format_stack + s = + Forth.new() + |> Forth.eval(": € 220371 ; €") + |> Forth.format_stack() + assert s == "220371" end @tag :pending test "defining a number" do assert_raise Forth.InvalidWord, fn -> - Forth.new |> Forth.eval(": 1 2 ;") + Forth.new() |> Forth.eval(": 1 2 ;") end end @tag :pending test "calling a non-existing word" do assert_raise Forth.UnknownWord, fn -> - Forth.new |> Forth.eval("1 foo") + Forth.new() |> Forth.eval("1 foo") end end end diff --git a/exercises/gigasecond/example.exs b/exercises/gigasecond/example.exs index eca42409a4..ee73458409 100644 --- a/exercises/gigasecond/example.exs +++ b/exercises/gigasecond/example.exs @@ -1,6 +1,6 @@ defmodule Gigasecond do def from(time) do seconds = :calendar.datetime_to_gregorian_seconds(time) - :calendar.gregorian_seconds_to_datetime(seconds + 1000000000) + :calendar.gregorian_seconds_to_datetime(seconds + 1_000_000_000) end end diff --git a/exercises/gigasecond/gigasecond.exs b/exercises/gigasecond/gigasecond.exs index eb822d8366..528634d902 100644 --- a/exercises/gigasecond/gigasecond.exs +++ b/exercises/gigasecond/gigasecond.exs @@ -2,9 +2,9 @@ defmodule Gigasecond do @doc """ Calculate a date one billion seconds after an input date. """ - @spec from({{pos_integer, pos_integer, pos_integer}, {pos_integer, pos_integer, pos_integer}}) :: :calendar.datetime + @spec from({{pos_integer, pos_integer, pos_integer}, {pos_integer, pos_integer, pos_integer}}) :: + :calendar.datetime() def from({{year, month, day}, {hours, minutes, seconds}}) do - end end diff --git a/exercises/gigasecond/gigasecond_test.exs b/exercises/gigasecond/gigasecond_test.exs index b45aee82a1..ed242b3ae8 100644 --- a/exercises/gigasecond/gigasecond_test.exs +++ b/exercises/gigasecond/gigasecond_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("gigasecond.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule GigasecondTest do use ExUnit.Case diff --git a/exercises/grade-school/example.exs b/exercises/grade-school/example.exs index b873a04fd7..2a52d53685 100644 --- a/exercises/grade-school/example.exs +++ b/exercises/grade-school/example.exs @@ -1,6 +1,6 @@ defmodule School do def add(db, name, grade) do - Map.update(db, grade, [name], &[name|&1]) + Map.update(db, grade, [name], &[name | &1]) end def grade(db, grade) do @@ -9,7 +9,7 @@ defmodule School do def sort(db) do db - |> Enum.map(fn {k,v} -> {k, Enum.sort(v)} end) - |> Enum.sort + |> Enum.map(fn {k, v} -> {k, Enum.sort(v)} end) + |> Enum.sort() end end diff --git a/exercises/grade-school/grade_school_test.exs b/exercises/grade-school/grade_school_test.exs index f4c7355ceb..a81087c72b 100644 --- a/exercises/grade-school/grade_school_test.exs +++ b/exercises/grade-school/grade_school_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("school.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule SchoolTest do use ExUnit.Case @@ -12,35 +12,38 @@ defmodule SchoolTest do test "add student" do actual = School.add(@db, "Aimee", 2) - assert actual == %{2 =>["Aimee"]} + assert actual == %{2 => ["Aimee"]} end @tag :pending test "add more students in same class" do - actual = @db - |> School.add("James", 2) - |> School.add("Blair", 2) - |> School.add("Paul", 2) + actual = + @db + |> School.add("James", 2) + |> School.add("Blair", 2) + |> School.add("Paul", 2) assert Enum.sort(actual[2]) == ["Blair", "James", "Paul"] end @tag :pending test "add students to different grades" do - actual = @db - |> School.add("Chelsea", 3) - |> School.add("Logan", 7) + actual = + @db + |> School.add("Chelsea", 3) + |> School.add("Logan", 7) assert actual == %{3 => ["Chelsea"], 7 => ["Logan"]} end @tag :pending test "get students in a grade" do - actual = @db - |> School.add("Bradley", 5) - |> School.add("Franklin", 5) - |> School.add("Jeff", 1) - |> School.grade(5) + actual = + @db + |> School.add("Bradley", 5) + |> School.add("Franklin", 5) + |> School.add("Jeff", 1) + |> School.grade(5) assert Enum.sort(actual) == ["Bradley", "Franklin"] end @@ -52,13 +55,14 @@ defmodule SchoolTest do @tag :pending test "sort school by grade and by student name" do - actual = @db - |> School.add("Bart", 4) - |> School.add("Jennifer", 4) - |> School.add("Christopher", 4) - |> School.add("Kareem", 6) - |> School.add("Kyle", 3) - |> School.sort + actual = + @db + |> School.add("Bart", 4) + |> School.add("Jennifer", 4) + |> School.add("Christopher", 4) + |> School.add("Kareem", 6) + |> School.add("Kyle", 3) + |> School.sort() expected = [ {3, ["Kyle"]}, diff --git a/exercises/grade-school/school.exs b/exercises/grade-school/school.exs index 0e1b2cdc14..4f20c5929f 100644 --- a/exercises/grade-school/school.exs +++ b/exercises/grade-school/school.exs @@ -8,24 +8,21 @@ defmodule School do @doc """ Add a student to a particular grade in school. """ - @spec add(map, String.t, integer) :: map + @spec add(map, String.t(), integer) :: map def add(db, name, grade) do - end @doc """ Return the names of the students in a particular grade. """ - @spec grade(map, integer) :: [String.t] + @spec grade(map, integer) :: [String.t()] def grade(db, grade) do - end @doc """ Sorts the school by grade and name. """ - @spec sort(map) :: [{integer, [String.t]}] + @spec sort(map) :: [{integer, [String.t()]}] def sort(db) do - end end diff --git a/exercises/grains/example.exs b/exercises/grains/example.exs index ee18098ea8..b89add74a4 100644 --- a/exercises/grains/example.exs +++ b/exercises/grains/example.exs @@ -1,6 +1,13 @@ defmodule Grains do use Bitwise, only_operators: true - def square(number) when number in (1..64), do: { :ok, 1 <<< (number - 1) } - def square(_), do: { :error, "The requested square must be between 1 and 64 (inclusive)" } - def total, do: { :ok, Enum.reduce(1..64, 0, fn(n, acc) -> {:ok, sq} = square(n); acc + sq end) } + def square(number) when number in 1..64, do: {:ok, 1 <<< (number - 1)} + def square(_), do: {:error, "The requested square must be between 1 and 64 (inclusive)"} + + def total, + do: + {:ok, + Enum.reduce(1..64, 0, fn n, acc -> + {:ok, sq} = square(n) + acc + sq + end)} end diff --git a/exercises/grains/grains.exs b/exercises/grains/grains.exs index 91704ee0c1..a6f37c2dc8 100644 --- a/exercises/grains/grains.exs +++ b/exercises/grains/grains.exs @@ -4,7 +4,6 @@ defmodule Grains do """ @spec square(pos_integer) :: pos_integer def square(number) do - end @doc """ @@ -12,6 +11,5 @@ defmodule Grains do """ @spec total :: pos_integer def total do - end end diff --git a/exercises/grains/grains_test.exs b/exercises/grains/grains_test.exs index d5c182b726..d21d11d6db 100644 --- a/exercises/grains/grains_test.exs +++ b/exercises/grains/grains_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("grains.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) # NOTE: :math.pow/2 doesn't do what you'd expect: # `:math.pow(2, 64) == :math.pow(2, 64) - 1` is true. @@ -16,57 +16,59 @@ defmodule GrainsTest do # @tag :pending test "square 1" do - assert Grains.square(1) === { :ok, 1 } + assert Grains.square(1) === {:ok, 1} end @tag :pending test "square 2" do - assert Grains.square(2) === { :ok, 2 } + assert Grains.square(2) === {:ok, 2} end @tag :pending test "square 3" do - assert Grains.square(3) === { :ok, 4 } + assert Grains.square(3) === {:ok, 4} end @tag :pending test "square 4" do - assert Grains.square(4) === { :ok, 8 } + assert Grains.square(4) === {:ok, 8} end @tag :pending test "square 16" do - assert Grains.square(16) === { :ok, 32768 } + assert Grains.square(16) === {:ok, 32768} end @tag :pending test "square 32" do - assert Grains.square(32) === { :ok, 2147483648 } + assert Grains.square(32) === {:ok, 2_147_483_648} end @tag :pending test "square 64" do - assert Grains.square(64) === { :ok, 9223372036854775808 } + assert Grains.square(64) === {:ok, 9_223_372_036_854_775_808} end @tag :pending test "total grains" do - assert Grains.total === { :ok, 18446744073709551615 } + assert Grains.total() === {:ok, 18_446_744_073_709_551_615} end @tag :pending test "square greater than 64 returns an error" do - assert Grains.square(65) === { :error, "The requested square must be between 1 and 64 (inclusive)" } + assert Grains.square(65) === + {:error, "The requested square must be between 1 and 64 (inclusive)"} end @tag :pending test "negative square returns an error" do - assert Grains.square(-1) === { :error, "The requested square must be between 1 and 64 (inclusive)" } + assert Grains.square(-1) === + {:error, "The requested square must be between 1 and 64 (inclusive)"} end @tag :pending test "square 0 returns an error" do - assert Grains.square(0) === { :error, "The requested square must be between 1 and 64 (inclusive)" } + assert Grains.square(0) === + {:error, "The requested square must be between 1 and 64 (inclusive)"} end - end diff --git a/exercises/grep/example.exs b/exercises/grep/example.exs index 86ea49c219..85359b810f 100644 --- a/exercises/grep/example.exs +++ b/exercises/grep/example.exs @@ -17,22 +17,25 @@ defmodule Grep do defp parse_flags(flags) do flags |> Enum.map(&parse_flag/1) - |> Enum.reduce(0, fn(a,b) -> a ||| b end) + |> Enum.reduce(0, fn a, b -> a ||| b end) end defp has_flag(flags, flag), do: (flags &&& flag) > 0 defp is_match(pattern, flags) do - pat = if has_flag(flags, @entire_lines) do - "^#{pattern}$" - else - pattern - end - cas = if has_flag(flags, @case_insensitive) do - "i" - else - "" - end + pat = + if has_flag(flags, @entire_lines) do + "^#{pattern}$" + else + pattern + end + + cas = + if has_flag(flags, @case_insensitive) do + "i" + else + "" + end regex = Regex.compile!(pat, cas) @@ -75,18 +78,19 @@ defmodule Grep do |> Enum.map(fmt) end - @spec grep(String.t, [String.t], [String.t]) :: String.t + @spec grep(String.t(), [String.t()], [String.t()]) :: String.t() def grep(pattern, flag_args, files) do flags = parse_flags(flag_args) - output = if has_flag(flags, @file_name) do - process_files(pattern, flags, files) - else - process_lines(pattern, flags, files) - end + output = + if has_flag(flags, @file_name) do + process_files(pattern, flags, files) + else + process_lines(pattern, flags, files) + end output |> Enum.map(fn l -> "#{l}\n" end) - |> Enum.reduce("", fn b,a -> "#{a}#{b}" end) + |> Enum.reduce("", fn b, a -> "#{a}#{b}" end) end end diff --git a/exercises/grep/grep.exs b/exercises/grep/grep.exs index 2f265cb69b..f210f27f76 100644 --- a/exercises/grep/grep.exs +++ b/exercises/grep/grep.exs @@ -1,6 +1,5 @@ defmodule Grep do - - @spec grep(String.t, [String.t], [String.t]) :: String.t + @spec grep(String.t(), [String.t()], [String.t()]) :: String.t() def grep(pattern, flags, files) do end end diff --git a/exercises/grep/grep_test.exs b/exercises/grep/grep_test.exs index 1da9b6e921..ad998765ec 100644 --- a/exercises/grep/grep_test.exs +++ b/exercises/grep/grep_test.exs @@ -2,14 +2,13 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("grep.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule GrepTest do use ExUnit.Case setup context do - if context[:files] do File.write!("iliad.txt", """ Achilles sing, O Goddess! Peleus' son; @@ -31,8 +30,7 @@ defmodule GrepTest do But I beseech your grace that I may know The worst that may befall me in this case, If I refuse to wed Demetrius. - """ - ) + """) File.write!("paradise-lost.txt", """ Of Mans First Disobedience, and the Fruit @@ -45,85 +43,82 @@ defmodule GrepTest do That Shepherd, who first taught the chosen Seed """) - on_exit fn -> + on_exit(fn -> File.rm!("iliad.txt") File.rm!("midsummer-night.txt") File.rm!("paradise-lost.txt") - end + end) end end @moduletag :files describe "grepping a single file" do - test "one match, no flags" do assert Grep.grep("Agamemnon", [], ["iliad.txt"]) == - """ - Of Atreus, Agamemnon, King of men. - """ + """ + Of Atreus, Agamemnon, King of men. + """ end @tag :pending test "one match, print line numbers flag" do assert Grep.grep("Forbidden", ["-n"], ["paradise-lost.txt"]) == - """ - 2:Of that Forbidden Tree, whose mortal tast - """ + """ + 2:Of that Forbidden Tree, whose mortal tast + """ end @tag :pending test "one match, case-insensitive flag" do assert Grep.grep("FORBIDDEN", ["-i"], ["paradise-lost.txt"]) == - """ - Of that Forbidden Tree, whose mortal tast - """ + """ + Of that Forbidden Tree, whose mortal tast + """ end @tag :pending test "one match, print file names flag" do assert Grep.grep("Forbidden", ["-l"], ["paradise-lost.txt"]) == - """ - paradise-lost.txt - """ + """ + paradise-lost.txt + """ end @tag :pending test "one match, match entire lines flag" do - assert Grep.grep("With loss of Eden, till one greater Man", - ["-x"], ["paradise-lost.txt"]) == - """ - With loss of Eden, till one greater Man - """ + assert Grep.grep("With loss of Eden, till one greater Man", ["-x"], ["paradise-lost.txt"]) == + """ + With loss of Eden, till one greater Man + """ end @tag :pending test "one match, multiple flags" do - assert Grep.grep("OF ATREUS, Agamemnon, KIng of MEN.", - ["-n", "-i", "-x"], ["iliad.txt"]) == - """ - 9:Of Atreus, Agamemnon, King of men. - """ + assert Grep.grep("OF ATREUS, Agamemnon, KIng of MEN.", ["-n", "-i", "-x"], ["iliad.txt"]) == + """ + 9:Of Atreus, Agamemnon, King of men. + """ end @tag :pending test "several matches, no flags" do assert Grep.grep("may", [], ["midsummer-night.txt"]) == - """ - Nor how it may concern my modesty, - But I beseech your grace that I may know - The worst that may befall me in this case, - """ + """ + Nor how it may concern my modesty, + But I beseech your grace that I may know + The worst that may befall me in this case, + """ end @tag :pending test "several matches, print line numbers flag" do assert Grep.grep("may", ["-n"], ["midsummer-night.txt"]) == - """ - 3:Nor how it may concern my modesty, - 5:But I beseech your grace that I may know - 6:The worst that may befall me in this case, - """ + """ + 3:Nor how it may concern my modesty, + 5:But I beseech your grace that I may know + 6:The worst that may befall me in this case, + """ end @tag :pending @@ -134,22 +129,22 @@ defmodule GrepTest do @tag :pending test "several matches, case-insensitive flag" do assert Grep.grep("ACHILLES", ["-i"], ["iliad.txt"]) == - """ - Achilles sing, O Goddess! Peleus' son; - The noble Chief Achilles from the son - """ + """ + Achilles sing, O Goddess! Peleus' son; + The noble Chief Achilles from the son + """ end @tag :pending test "several matches, inverted flag" do assert Grep.grep("Of", ["-v"], ["paradise-lost.txt"]) == - """ - Brought Death into the World, and all our woe, - With loss of Eden, till one greater Man - Restore us, and regain the blissful Seat, - Sing Heav'nly Muse, that on the secret top - That Shepherd, who first taught the chosen Seed - """ + """ + Brought Death into the World, and all our woe, + With loss of Eden, till one greater Man + Restore us, and regain the blissful Seat, + Sing Heav'nly Muse, that on the secret top + That Shepherd, who first taught the chosen Seed + """ end @tag :pending @@ -159,101 +154,102 @@ defmodule GrepTest do end describe "grepping multiples files at once" do - @tag :pending test "one match, no flags" do - assert Grep.grep("Agamemnon", [], - ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == - """ - iliad.txt:Of Atreus, Agamemnon, King of men. - """ + assert Grep.grep("Agamemnon", [], ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == + """ + iliad.txt:Of Atreus, Agamemnon, King of men. + """ end @tag :pending test "several matches, no flags" do - assert Grep.grep("may", [], - ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == - """ - midsummer-night.txt:Nor how it may concern my modesty, - midsummer-night.txt:But I beseech your grace that I may know - midsummer-night.txt:The worst that may befall me in this case, - """ + assert Grep.grep("may", [], ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == + """ + midsummer-night.txt:Nor how it may concern my modesty, + midsummer-night.txt:But I beseech your grace that I may know + midsummer-night.txt:The worst that may befall me in this case, + """ end @tag :pending test "several matches, print line numbers flag" do - assert Grep.grep("that", ["-n"], - ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == - """ - midsummer-night.txt:5:But I beseech your grace that I may know - midsummer-night.txt:6:The worst that may befall me in this case, - paradise-lost.txt:2:Of that Forbidden Tree, whose mortal tast - paradise-lost.txt:6:Sing Heav'nly Muse, that on the secret top - """ + assert Grep.grep("that", ["-n"], ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == + """ + midsummer-night.txt:5:But I beseech your grace that I may know + midsummer-night.txt:6:The worst that may befall me in this case, + paradise-lost.txt:2:Of that Forbidden Tree, whose mortal tast + paradise-lost.txt:6:Sing Heav'nly Muse, that on the secret top + """ end @tag :pending test "one match, print file names flag" do - assert Grep.grep("who", ["-l"], - ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == - """ - iliad.txt - paradise-lost.txt - """ + assert Grep.grep("who", ["-l"], ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == + """ + iliad.txt + paradise-lost.txt + """ end @tag :pending test "several matches, case-insensitive flag" do - assert Grep.grep("TO", ["-i"], - ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == - """ - iliad.txt:Caused to Achaia's host, sent many a soul - iliad.txt:Illustrious into Ades premature, - iliad.txt:And Heroes gave (so stood the will of Jove) - iliad.txt:To dogs and to all ravening fowls a prey, - midsummer-night.txt:I do entreat your grace to pardon me. - midsummer-night.txt:In such a presence here to plead my thoughts; - midsummer-night.txt:If I refuse to wed Demetrius. - paradise-lost.txt:Brought Death into the World, and all our woe, - paradise-lost.txt:Restore us, and regain the blissful Seat, - paradise-lost.txt:Sing Heav'nly Muse, that on the secret top - """ + assert Grep.grep("TO", ["-i"], ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == + """ + iliad.txt:Caused to Achaia's host, sent many a soul + iliad.txt:Illustrious into Ades premature, + iliad.txt:And Heroes gave (so stood the will of Jove) + iliad.txt:To dogs and to all ravening fowls a prey, + midsummer-night.txt:I do entreat your grace to pardon me. + midsummer-night.txt:In such a presence here to plead my thoughts; + midsummer-night.txt:If I refuse to wed Demetrius. + paradise-lost.txt:Brought Death into the World, and all our woe, + paradise-lost.txt:Restore us, and regain the blissful Seat, + paradise-lost.txt:Sing Heav'nly Muse, that on the secret top + """ end @tag :pending test "several matches, inverted flag" do - assert Grep.grep("a", ["-v"], - ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == - """ - iliad.txt:Achilles sing, O Goddess! Peleus' son; - iliad.txt:The noble Chief Achilles from the son - midsummer-night.txt:If I refuse to wed Demetrius. - """ + assert Grep.grep("a", ["-v"], ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == + """ + iliad.txt:Achilles sing, O Goddess! Peleus' son; + iliad.txt:The noble Chief Achilles from the son + midsummer-night.txt:If I refuse to wed Demetrius. + """ end @tag :pending test "one match, match entire lines flag" do - assert Grep.grep("But I beseech your grace that I may know", ["-x"], - ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == - """ - midsummer-night.txt:But I beseech your grace that I may know - """ + assert Grep.grep("But I beseech your grace that I may know", ["-x"], [ + "iliad.txt", + "midsummer-night.txt", + "paradise-lost.txt" + ]) == + """ + midsummer-night.txt:But I beseech your grace that I may know + """ end @tag :pending test "one match, multiple flags" do - assert Grep.grep("WITH LOSS OF EDEN, TILL ONE GREATER MAN", - ["-n", "-x", "-i"], - ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == - """ - paradise-lost.txt:4:With loss of Eden, till one greater Man - """ + assert Grep.grep("WITH LOSS OF EDEN, TILL ONE GREATER MAN", ["-n", "-x", "-i"], [ + "iliad.txt", + "midsummer-night.txt", + "paradise-lost.txt" + ]) == + """ + paradise-lost.txt:4:With loss of Eden, till one greater Man + """ end @tag :pending test "no matches, various flags" do - assert Grep.grep("Frodo", ["-n", "-l", "-x", "i"], - ["iliad.txt", "midsummer-night.txt", "paradise-lost.txt"]) == "" + assert Grep.grep("Frodo", ["-n", "-l", "-x", "i"], [ + "iliad.txt", + "midsummer-night.txt", + "paradise-lost.txt" + ]) == "" end end end diff --git a/exercises/hamming/example.exs b/exercises/hamming/example.exs index 4389aea4e7..2240412d33 100644 --- a/exercises/hamming/example.exs +++ b/exercises/hamming/example.exs @@ -11,8 +11,9 @@ defmodule Hamming do distance = pairs(strand1, strand2) |> count_mismatched {:ok, distance} end + def hamming_distance(_, _), do: {:error, "Lists must be the same length"} - defp pairs(s1, s2), do: Enum.zip(s1, s2) - defp count_mismatched(pairs), do: Enum.count(pairs, fn({c1, c2}) -> c2 && (c1 != c2) end) + defp pairs(s1, s2), do: Enum.zip(s1, s2) + defp count_mismatched(pairs), do: Enum.count(pairs, fn {c1, c2} -> c2 && c1 != c2 end) end diff --git a/exercises/hamming/hamming_test.exs b/exercises/hamming/hamming_test.exs index 8e74b76bf0..7c0e1dc6a5 100644 --- a/exercises/hamming/hamming_test.exs +++ b/exercises/hamming/hamming_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("hamming.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule HammingTest do use ExUnit.Case @@ -34,7 +34,10 @@ defmodule HammingTest do @tag :pending test "hamming distance is undefined for strands of different lengths" do - assert {:error, "Lists must be the same length"} = Hamming.hamming_distance('AAAC', 'TAGGGGAGGCTAGCGGTAGGAC') - assert {:error, "Lists must be the same length"} = Hamming.hamming_distance('GACTACGGACAGGACACC', 'GACATCGC') + assert {:error, "Lists must be the same length"} = + Hamming.hamming_distance('AAAC', 'TAGGGGAGGCTAGCGGTAGGAC') + + assert {:error, "Lists must be the same length"} = + Hamming.hamming_distance('GACTACGGACAGGACACC', 'GACATCGC') end end diff --git a/exercises/hello-world/example.exs b/exercises/hello-world/example.exs index 13155a6ce5..c799c145df 100644 --- a/exercises/hello-world/example.exs +++ b/exercises/hello-world/example.exs @@ -6,4 +6,4 @@ defmodule HelloWorld do def hello do "Hello, World!" end - end +end diff --git a/exercises/hello-world/hello_world.exs b/exercises/hello-world/hello_world.exs index 6c9ac1c052..82ecb3f2f3 100644 --- a/exercises/hello-world/hello_world.exs +++ b/exercises/hello-world/hello_world.exs @@ -2,7 +2,7 @@ defmodule HelloWorld do @doc """ Simply returns "Hello, World!" """ - @spec hello :: String.t + @spec hello :: String.t() def hello do "Your implementation goes here" end diff --git a/exercises/hello-world/hello_world_test.exs b/exercises/hello-world/hello_world_test.exs index d91c51f7b7..6b3dfbb04f 100644 --- a/exercises/hello-world/hello_world_test.exs +++ b/exercises/hello-world/hello_world_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("hello_world.exs", __DIR__) end -ExUnit.start -ExUnit.configure trace: true +ExUnit.start() +ExUnit.configure(trace: true) defmodule HelloWorldTest do use ExUnit.Case diff --git a/exercises/hexadecimal/example.exs b/exercises/hexadecimal/example.exs index c7df521835..1b315fd933 100644 --- a/exercises/hexadecimal/example.exs +++ b/exercises/hexadecimal/example.exs @@ -1,8 +1,8 @@ defmodule Hexadecimal do @base 16 @hex_table String.split("0123456789abcdef", "", trim: true) - |> Enum.with_index - |> Enum.into(%{}) + |> Enum.with_index() + |> Enum.into(%{}) @doc """ Accept a string representing a hexadecimal value and return the @@ -26,10 +26,10 @@ defmodule Hexadecimal do 0 else hex - |> String.downcase - |> String.reverse - |> String.split("", trim: true) - |> hex_to_int(0, 0) + |> String.downcase() + |> String.reverse() + |> String.split("", trim: true) + |> hex_to_int(0, 0) end end @@ -38,7 +38,8 @@ defmodule Hexadecimal do end defp hex_to_int([], acc, _), do: round(acc) - defp hex_to_int([char|hex], acc, power) do + + defp hex_to_int([char | hex], acc, power) do acc = acc + Map.get(@hex_table, char) * :math.pow(@base, power) hex_to_int(hex, acc, power + 1) end diff --git a/exercises/hexadecimal/hexadecimal.exs b/exercises/hexadecimal/hexadecimal.exs index ed0cb82f11..6ac6af254b 100644 --- a/exercises/hexadecimal/hexadecimal.exs +++ b/exercises/hexadecimal/hexadecimal.exs @@ -17,6 +17,5 @@ defmodule Hexadecimal do @spec to_decimal(binary) :: integer def to_decimal(hex) do - end end diff --git a/exercises/hexadecimal/hexadecimal_test.exs b/exercises/hexadecimal/hexadecimal_test.exs index 5dd2484586..bf7c21abd5 100644 --- a/exercises/hexadecimal/hexadecimal_test.exs +++ b/exercises/hexadecimal/hexadecimal_test.exs @@ -2,14 +2,14 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("hexadecimal.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule HexadecimalTest do use ExUnit.Case test "returns 1 when hex is 1" do - assert Hexadecimal.to_decimal("1") == 1 + assert Hexadecimal.to_decimal("1") == 1 end @tag :pending diff --git a/exercises/isbn-verifier/example.exs b/exercises/isbn-verifier/example.exs index 832a494854..0c83d79e10 100644 --- a/exercises/isbn-verifier/example.exs +++ b/exercises/isbn-verifier/example.exs @@ -33,4 +33,4 @@ defmodule ISBNVerifier do defp checksum_weighting({digit, weight}) do String.to_integer(digit) * weight end -end \ No newline at end of file +end diff --git a/exercises/isbn-verifier/isbn_verifier.exs b/exercises/isbn-verifier/isbn_verifier.exs index 0dfc723658..5e6ad04ba3 100644 --- a/exercises/isbn-verifier/isbn_verifier.exs +++ b/exercises/isbn-verifier/isbn_verifier.exs @@ -13,6 +13,5 @@ defmodule ISBNVerifier do """ @spec isbn?(String.t()) :: boolean def isbn?(isbn) do - end -end \ No newline at end of file +end diff --git a/exercises/isbn-verifier/isbn_verifier_test.exs b/exercises/isbn-verifier/isbn_verifier_test.exs index 7445b91720..44239836ec 100644 --- a/exercises/isbn-verifier/isbn_verifier_test.exs +++ b/exercises/isbn-verifier/isbn_verifier_test.exs @@ -8,7 +8,7 @@ ExUnit.configure(exclude: :pending, trace: true) defmodule ISBNVerifierTest do use ExUnit.Case - #@tag :pending + # @tag :pending test "valid isbn number" do assert ISBNVerifier.isbn?("3-598-21508-8") end @@ -72,4 +72,4 @@ defmodule ISBNVerifierTest do test "check digit of X should not be used for 0" do refute ISBNVerifier.isbn?("3-598-21515-X") end -end \ No newline at end of file +end diff --git a/exercises/isogram/example.exs b/exercises/isogram/example.exs index 12fb8ba610..ed01539781 100644 --- a/exercises/isogram/example.exs +++ b/exercises/isogram/example.exs @@ -2,14 +2,14 @@ defmodule Isogram do @doc """ Determines if a word or sentence is an isogram """ - @spec isogram?(String.t) :: boolean + @spec isogram?(String.t()) :: boolean def isogram?(sentence) do - codepoints = sentence - |> String.downcase + codepoints = + sentence + |> String.downcase() |> String.replace(~r/\s|-/u, "") - |> String.codepoints + |> String.codepoints() length(Enum.uniq(codepoints)) == length(codepoints) end - end diff --git a/exercises/isogram/isogram.exs b/exercises/isogram/isogram.exs index c636d5ab63..75826df0db 100644 --- a/exercises/isogram/isogram.exs +++ b/exercises/isogram/isogram.exs @@ -2,9 +2,7 @@ defmodule Isogram do @doc """ Determines if a word or sentence is an isogram """ - @spec isogram?(String.t) :: boolean + @spec isogram?(String.t()) :: boolean def isogram?(sentence) do - end - end diff --git a/exercises/isogram/isogram_test.exs b/exercises/isogram/isogram_test.exs index ba6e6925bd..7fd54b950f 100644 --- a/exercises/isogram/isogram_test.exs +++ b/exercises/isogram/isogram_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("isogram.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule IsogramTest do use ExUnit.Case @@ -46,5 +46,4 @@ defmodule IsogramTest do test "phrase is not isogram" do refute Isogram.isogram?("the quick brown fox") end - end diff --git a/exercises/kindergarten-garden/example.exs b/exercises/kindergarten-garden/example.exs index 4f0fe3e274..2cf47fe59c 100644 --- a/exercises/kindergarten-garden/example.exs +++ b/exercises/kindergarten-garden/example.exs @@ -1,6 +1,18 @@ defmodule Garden do - @default_names [:alice, :bob, :charlie, :david, :eve, :fred, :ginny, :harriet, - :ileana, :joseph, :kincaid, :larry] + @default_names [ + :alice, + :bob, + :charlie, + :david, + :eve, + :fred, + :ginny, + :harriet, + :ileana, + :joseph, + :kincaid, + :larry + ] @letter_map %{"V" => :violets, "R" => :radishes, "C" => :clover, "G" => :grass} @doc """ @@ -46,7 +58,7 @@ defmodule Garden do defp add_to_map(map, current_name, letters) do letters = String.codepoints(letters) - translated_list = Enum.map(letters, fn(letter) -> @letter_map[letter] end) + translated_list = Enum.map(letters, fn letter -> @letter_map[letter] end) tuple = List.to_tuple(translated_list) Map.put(map, current_name, tuple) end diff --git a/exercises/kindergarten-garden/garden_test.exs b/exercises/kindergarten-garden/garden_test.exs index 692f3b01d9..d635314900 100644 --- a/exercises/kindergarten-garden/garden_test.exs +++ b/exercises/kindergarten-garden/garden_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("garden.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule GardenTest do use ExUnit.Case @@ -57,8 +57,21 @@ defmodule GardenTest do @tag :pending test "gets the garden for all students with custom child names" do - names = [:maggie, :nate, :xander, :ophelia, :pete, :reggie, :sylvia, - :tanner, :ursula, :victor, :winnie, :ynold] + names = [ + :maggie, + :nate, + :xander, + :ophelia, + :pete, + :reggie, + :sylvia, + :tanner, + :ursula, + :victor, + :winnie, + :ynold + ] + garden_string = "VRCGVVRVCGGCCGVRGCVCGCGV\nVRCCCGCRRGVCGCRVVCVGCGCV" garden_info = Garden.info(garden_string, names) assert garden_info.maggie == {:violets, :radishes, :violets, :radishes} diff --git a/exercises/largest-series-product/example.exs b/exercises/largest-series-product/example.exs index 9db358df31..0150365b7b 100644 --- a/exercises/largest-series-product/example.exs +++ b/exercises/largest-series-product/example.exs @@ -1,17 +1,16 @@ defmodule Series do - - @spec digits(String.t) :: [non_neg_integer] + @spec digits(String.t()) :: [non_neg_integer] defp digits("") do [] end defp digits(number_string) do String.split(number_string, "", trim: true) - |> Enum.reduce([], fn(char, acc) -> [String.to_integer(char)|acc] end) - |> Enum.reverse + |> Enum.reduce([], fn char, acc -> [String.to_integer(char) | acc] end) + |> Enum.reverse() end - @spec slices(String.t, non_neg_integer) :: [list(non_neg_integer)] + @spec slices(String.t(), non_neg_integer) :: [list(non_neg_integer)] defp slices(number_string, size) do digits = digits(number_string) chunk(digits, size, 1) @@ -20,7 +19,7 @@ defmodule Series do @doc """ Finds the largest product of a given number of consecutive numbers in a given string of numbers. """ - @spec largest_product(String.t, non_neg_integer) :: non_neg_integer + @spec largest_product(String.t(), non_neg_integer) :: non_neg_integer def largest_product(_, 0) do 1 end @@ -29,13 +28,15 @@ defmodule Series do unless Enum.member?(Range.new(0, String.length(number_string)), size) do raise ArgumentError end + slices = slices(number_string, size) - Enum.map(slices, &Enum.reduce(&1, fn(x, acc) -> x * acc end)) - |> Enum.max + + Enum.map(slices, &Enum.reduce(&1, fn x, acc -> x * acc end)) + |> Enum.max() end # Handle Enum.chunks -> Enum.chunk renaming. - if not { :chunk, 3 } in Enum.__info__(:functions) do + if not ({:chunk, 3} in Enum.__info__(:functions)) do defp chunk(coll, n, step), do: Enum.chunks(coll, n, step) else defp chunk(coll, n, step), do: Enum.chunk(coll, n, step) diff --git a/exercises/largest-series-product/largest_series_product.exs b/exercises/largest-series-product/largest_series_product.exs index 7e0c4cfe71..8fdfc4d9ef 100644 --- a/exercises/largest-series-product/largest_series_product.exs +++ b/exercises/largest-series-product/largest_series_product.exs @@ -1,10 +1,8 @@ defmodule Series do - @doc """ Finds the largest product of a given number of consecutive numbers in a given string of numbers. """ - @spec largest_product(String.t, non_neg_integer) :: non_neg_integer + @spec largest_product(String.t(), non_neg_integer) :: non_neg_integer def largest_product(number_string, size) do - end end diff --git a/exercises/largest-series-product/largest_series_product_test.exs b/exercises/largest-series-product/largest_series_product_test.exs index 2a14b5ac10..b4cd4184b7 100644 --- a/exercises/largest-series-product/largest_series_product_test.exs +++ b/exercises/largest-series-product/largest_series_product_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("largest_series_product.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule LargestSeriesProductTest do use ExUnit.Case @@ -45,12 +45,14 @@ defmodule LargestSeriesProductTest do @tag :pending test "some big number" do - assert Series.largest_product("73167176531330624919225119674426574742355349194934", 6) == 23520 + assert Series.largest_product("73167176531330624919225119674426574742355349194934", 6) == + 23520 end @tag :pending test "some other big number" do - assert Series.largest_product("52677741234314237566414902593461595376319419139427", 6) == 28350 + assert Series.largest_product("52677741234314237566414902593461595376319419139427", 6) == + 28350 end @tag :pending diff --git a/exercises/leap/example.exs b/exercises/leap/example.exs index e8ccd4833f..604db57c79 100644 --- a/exercises/leap/example.exs +++ b/exercises/leap/example.exs @@ -1,10 +1,10 @@ defmodule Year do def leap_year?(year) do - div4?(year) && (div100?(year) == div400?(year)) + div4?(year) && div100?(year) == div400?(year) end defp divides?(dividend, divisor), do: rem(dividend, divisor) == 0 - defp div4?(dividend), do: divides?(dividend, 4) + defp div4?(dividend), do: divides?(dividend, 4) defp div100?(dividend), do: divides?(dividend, 100) defp div400?(dividend), do: divides?(dividend, 400) end diff --git a/exercises/leap/leap.exs b/exercises/leap/leap.exs index 2de3ce126a..31d1e86e8d 100644 --- a/exercises/leap/leap.exs +++ b/exercises/leap/leap.exs @@ -10,6 +10,5 @@ defmodule Year do """ @spec leap_year?(non_neg_integer) :: boolean def leap_year?(year) do - end end diff --git a/exercises/leap/leap_test.exs b/exercises/leap/leap_test.exs index 755b4370be..ddf1960f66 100644 --- a/exercises/leap/leap_test.exs +++ b/exercises/leap/leap_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("leap.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule LeapTest do use ExUnit.Case diff --git a/exercises/list-ops/example.exs b/exercises/list-ops/example.exs index a4e50caaa4..a917d91413 100644 --- a/exercises/list-ops/example.exs +++ b/exercises/list-ops/example.exs @@ -10,43 +10,44 @@ defmodule ListOps do def count(l), do: do_count(l, 0) defp do_count([], acc), do: acc - defp do_count([_|t], acc), do: do_count(t, acc+1) + defp do_count([_ | t], acc), do: do_count(t, acc + 1) @spec reverse(list) :: list def reverse(l), do: do_reverse(l, []) defp do_reverse([], acc), do: acc - defp do_reverse([h|t], acc), do: do_reverse(t, [h|acc]) + defp do_reverse([h | t], acc), do: do_reverse(t, [h | acc]) @spec map(list, (any -> any)) :: list def map(l, f), do: do_map(l, f, []) |> reverse() defp do_map([], _, acc), do: acc - defp do_map([h|t], f, acc), do: do_map(t, f, [f.(h)|acc]) + defp do_map([h | t], f, acc), do: do_map(t, f, [f.(h) | acc]) @spec filter(list, (any -> as_boolean(term))) :: list def filter(l, f), do: do_filter(l, f, []) |> reverse() defp do_filter([], _, acc), do: acc - defp do_filter([h|t], f, acc) do + + defp do_filter([h | t], f, acc) do if f.(h) do - do_filter(t, f, [h|acc]) + do_filter(t, f, [h | acc]) else do_filter(t, f, acc) end end @type acc :: any - @spec reduce(list, acc, ((any, acc) -> acc)) :: acc + @spec reduce(list, acc, (any, acc -> acc)) :: acc def reduce([], acc, _), do: acc - def reduce([h|t], acc, f), do: reduce(t, f.(h, acc), f) + def reduce([h | t], acc, f), do: reduce(t, f.(h, acc), f) @spec append(list, list) :: list def append(a, b), do: do_append(reverse(a), b) defp do_append([], b), do: b - defp do_append([h|t], b), do: do_append(t, [h|b]) + defp do_append([h | t], b), do: do_append(t, [h | b]) @spec concat([[any]]) :: [any] - def concat(ll), do: reverse(ll) |> reduce([], &(append(&1, &2))) + def concat(ll), do: reverse(ll) |> reduce([], &append(&1, &2)) end diff --git a/exercises/list-ops/list_ops.exs b/exercises/list-ops/list_ops.exs index 24e544e854..08c56f646b 100644 --- a/exercises/list-ops/list_ops.exs +++ b/exercises/list-ops/list_ops.exs @@ -8,37 +8,30 @@ defmodule ListOps do @spec count(list) :: non_neg_integer def count(l) do - end @spec reverse(list) :: list def reverse(l) do - end @spec map(list, (any -> any)) :: list def map(l, f) do - end @spec filter(list, (any -> as_boolean(term))) :: list def filter(l, f) do - end @type acc :: any - @spec reduce(list, acc, ((any, acc) -> acc)) :: acc + @spec reduce(list, acc, (any, acc -> acc)) :: acc def reduce(l, acc, f) do - end @spec append(list, list) :: list def append(a, b) do - end @spec concat([[any]]) :: [any] def concat(ll) do - end end diff --git a/exercises/list-ops/list_ops_test.exs b/exercises/list-ops/list_ops_test.exs index c04bc7acc5..b0ad1b39f0 100644 --- a/exercises/list-ops/list_ops_test.exs +++ b/exercises/list-ops/list_ops_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("list_ops.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule ListOpsTest do alias ListOps, as: L @@ -19,7 +19,7 @@ defmodule ListOpsTest do @tag :pending test "count of normal list" do - assert L.count([1,3,5,7]) == 4 + assert L.count([1, 3, 5, 7]) == 4 end @tag :pending @@ -34,7 +34,7 @@ defmodule ListOpsTest do @tag :pending test "reverse of normal list" do - assert L.reverse([1,3,5,7]) == [7,5,3,1] + assert L.reverse([1, 3, 5, 7]) == [7, 5, 3, 1] end @tag :pending @@ -44,18 +44,17 @@ defmodule ListOpsTest do @tag :pending test "map of empty list" do - assert L.map([], &(&1+1)) == [] + assert L.map([], &(&1 + 1)) == [] end @tag :pending test "map of normal list" do - assert L.map([1,3,5,7], &(&1+1)) == [2,4,6,8] + assert L.map([1, 3, 5, 7], &(&1 + 1)) == [2, 4, 6, 8] end @tag :pending test "map of huge list" do - assert L.map(Enum.to_list(1..1_000_000), &(&1+1)) == - Enum.to_list(2..1_000_001) + assert L.map(Enum.to_list(1..1_000_000), &(&1 + 1)) == Enum.to_list(2..1_000_001) end @tag :pending @@ -65,34 +64,33 @@ defmodule ListOpsTest do @tag :pending test "filter of normal list" do - assert L.filter([1,2,3,4], &odd?/1) == [1,3] + assert L.filter([1, 2, 3, 4], &odd?/1) == [1, 3] end @tag :pending test "filter of huge list" do - assert L.filter(Enum.to_list(1..1_000_000), &odd?/1) == - Enum.map(1..500_000, &(&1*2-1)) + assert L.filter(Enum.to_list(1..1_000_000), &odd?/1) == Enum.map(1..500_000, &(&1 * 2 - 1)) end @tag :pending test "reduce of empty list" do - assert L.reduce([], 0, &(&1+&2)) == 0 + assert L.reduce([], 0, &(&1 + &2)) == 0 end @tag :pending test "reduce of normal list" do - assert L.reduce([1,2,3,4], -3, &(&1+&2)) == 7 + assert L.reduce([1, 2, 3, 4], -3, &(&1 + &2)) == 7 end @tag :pending test "reduce of huge list" do - assert L.reduce(Enum.to_list(1..1_000_000), 0, &(&1+&2)) == - Enum.reduce(1..1_000_000, 0, &(&1+&2)) + assert L.reduce(Enum.to_list(1..1_000_000), 0, &(&1 + &2)) == + Enum.reduce(1..1_000_000, 0, &(&1 + &2)) end @tag :pending test "reduce with non-commutative function" do - assert L.reduce([1,2,3,4], 10, fn x, acc -> acc - x end) == 0 + assert L.reduce([1, 2, 3, 4], 10, fn x, acc -> acc - x end) == 0 end @tag :pending @@ -102,23 +100,23 @@ defmodule ListOpsTest do @tag :pending test "append of empty and non-empty list" do - assert L.append([], [1,2,3,4]) == [1,2,3,4] + assert L.append([], [1, 2, 3, 4]) == [1, 2, 3, 4] end @tag :pending test "append of non-empty and empty list" do - assert L.append([1,2,3,4], []) == [1,2,3,4] + assert L.append([1, 2, 3, 4], []) == [1, 2, 3, 4] end @tag :pending test "append of non-empty lists" do - assert L.append([1,2,3], [4,5]) == [1,2,3,4,5] + assert L.append([1, 2, 3], [4, 5]) == [1, 2, 3, 4, 5] end @tag :pending test "append of huge lists" do assert L.append(Enum.to_list(1..1_000_000), Enum.to_list(1_000_001..2_000_000)) == - Enum.to_list(1..2_000_000) + Enum.to_list(1..2_000_000) end @tag :pending @@ -128,18 +126,17 @@ defmodule ListOpsTest do @tag :pending test "concat of normal list of lists" do - assert L.concat([[1,2],[3],[],[4,5,6]]) == [1,2,3,4,5,6] + assert L.concat([[1, 2], [3], [], [4, 5, 6]]) == [1, 2, 3, 4, 5, 6] end @tag :pending test "concat of huge list of small lists" do - assert L.concat(Enum.map(1..1_000_000, &[&1])) == - Enum.to_list(1..1_000_000) + assert L.concat(Enum.map(1..1_000_000, &[&1])) == Enum.to_list(1..1_000_000) end @tag :pending test "concat of small list of huge lists" do - assert L.concat(Enum.map(0..9, &Enum.to_list((&1*100_000+1)..((&1+1)*100_000)))) == - Enum.to_list(1..1_000_000) + assert L.concat(Enum.map(0..9, &Enum.to_list((&1 * 100_000 + 1)..((&1 + 1) * 100_000)))) == + Enum.to_list(1..1_000_000) end end diff --git a/exercises/luhn/example.exs b/exercises/luhn/example.exs index ecd9a41688..2338991972 100644 --- a/exercises/luhn/example.exs +++ b/exercises/luhn/example.exs @@ -1,39 +1,38 @@ defmodule Luhn do - @doc """ Checks if the given number is valid via the luhn formula """ @spec valid?(String.t()) :: boolean def valid?(number) do number_without_spaces = String.replace(number, " ", "") + case Integer.parse(number_without_spaces) do {_, ""} -> String.length(number_without_spaces) > 1 && checksum(number_without_spaces) + _ -> false end end defp checksum(number) do - 0 == number - |> String.graphemes() - |> Enum.map(&String.to_integer/1) - |> double_even() - |> Enum.sum() - |> rem(10) + 0 == + number + |> String.graphemes() + |> Enum.map(&String.to_integer/1) + |> double_even() + |> Enum.sum() + |> rem(10) end defp double_even(numlist) do numlist |> Enum.reverse() - |> Enum.zip(Stream.cycle([1,2])) - |> Enum.map(fn {n,m} -> n * m end) - |> Enum.map( - fn - n when n > 9 -> n-9 - n -> n - end) - + |> Enum.zip(Stream.cycle([1, 2])) + |> Enum.map(fn {n, m} -> n * m end) + |> Enum.map(fn + n when n > 9 -> n - 9 + n -> n + end) end - -end \ No newline at end of file +end diff --git a/exercises/luhn/luhn.exs b/exercises/luhn/luhn.exs index 2d92ca2398..e00556bcd1 100644 --- a/exercises/luhn/luhn.exs +++ b/exercises/luhn/luhn.exs @@ -1,10 +1,8 @@ defmodule Luhn do - @doc """ Checks if the given number is valid via the luhn formula """ @spec valid?(String.t()) :: boolean def valid?(number) do end - end diff --git a/exercises/luhn/luhn_test.exs b/exercises/luhn/luhn_test.exs index 88d6a599fd..d0945f9034 100644 --- a/exercises/luhn/luhn_test.exs +++ b/exercises/luhn/luhn_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("luhn.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule LuhnTest do use ExUnit.Case diff --git a/exercises/markdown/example.exs b/exercises/markdown/example.exs index c9d76cd329..aee8510fb3 100644 --- a/exercises/markdown/example.exs +++ b/exercises/markdown/example.exs @@ -22,14 +22,20 @@ defmodule Markdown do end defp parse_line(markdown_split_by_newline) do - Enum.map_join(markdown_split_by_newline, fn(text_with_md) -> process_md(text_with_md) end) |> patch_line_with_unordered_list_tag + Enum.map_join(markdown_split_by_newline, fn text_with_md -> process_md(text_with_md) end) + |> patch_line_with_unordered_list_tag end defp process_md(text_with_md) do cond do - String.starts_with?(text_with_md, @header_md) -> parse_header_md_level(text_with_md) |> enclose_with_header_tag - String.starts_with?(text_with_md, @list_md) -> parse_list_md_level(text_with_md) - true -> String.split(text_with_md) |> enclose_with_paragraph_tag + String.starts_with?(text_with_md, @header_md) -> + parse_header_md_level(text_with_md) |> enclose_with_header_tag + + String.starts_with?(text_with_md, @list_md) -> + parse_list_md_level(text_with_md) + + true -> + String.split(text_with_md) |> enclose_with_paragraph_tag end end @@ -39,12 +45,13 @@ defmodule Markdown do end defp parse_list_md_level(list_md_with_text) do - list_text = String.trim_leading(list_md_with_text, "* ") |> String.split + list_text = String.trim_leading(list_md_with_text, "* ") |> String.split() @list_item_open_tag <> join_words_with_tags(list_text) <> @list_item_close_tag end defp enclose_with_header_tag({header_level, header_text_line}) do - @header_partial_open_tag <> header_level <> ">" <> header_text_line <> @header_partial_close_tag <> header_level <> ">" + @header_partial_open_tag <> + header_level <> ">" <> header_text_line <> @header_partial_close_tag <> header_level <> ">" end defp enclose_with_paragraph_tag(text_with_md) do @@ -52,7 +59,7 @@ defmodule Markdown do end defp join_words_with_tags(text_with_md) do - Enum.map_join(text_with_md, " ", fn(word_with_md) -> replace_md_with_tag(word_with_md) end) + Enum.map_join(text_with_md, " ", fn word_with_md -> replace_md_with_tag(word_with_md) end) end defp replace_md_with_tag(word_with_md) do @@ -61,21 +68,40 @@ defmodule Markdown do defp replace_prefix_md(word_with_md) do cond do - word_with_md =~ ~r/^[#{@italic_md}{1}][^#{@italic_md}+]/ -> String.replace_prefix(word_with_md, @italic_md, @italic_open_tag) - word_with_md =~ ~r/^#{@bold_md}{1}/ -> String.replace_prefix(word_with_md, @bold_md, @bold_open_tag) - true -> word_with_md + word_with_md =~ ~r/^[#{@italic_md}{1}][^#{@italic_md}+]/ -> + String.replace_prefix(word_with_md, @italic_md, @italic_open_tag) + + word_with_md =~ ~r/^#{@bold_md}{1}/ -> + String.replace_prefix(word_with_md, @bold_md, @bold_open_tag) + + true -> + word_with_md end end defp replace_suffix_md(word_with_md) do cond do - word_with_md =~ ~r/[^#{@italic_md}{1}][#{@italic_md}{1}]$/ -> String.replace_suffix(word_with_md, @italic_md, @italic_close_tag) - word_with_md =~ ~r/#{@bold_md}{1}$/ -> String.replace_suffix(word_with_md, @bold_md, @bold_close_tag) - true -> word_with_md + word_with_md =~ ~r/[^#{@italic_md}{1}][#{@italic_md}{1}]$/ -> + String.replace_suffix(word_with_md, @italic_md, @italic_close_tag) + + word_with_md =~ ~r/#{@bold_md}{1}$/ -> + String.replace_suffix(word_with_md, @bold_md, @bold_close_tag) + + true -> + word_with_md end end defp patch_line_with_unordered_list_tag(html_line) do - String.replace(html_line, @list_item_open_tag, @unordered_list_open_tag <> @list_item_open_tag, global: false) |> String.replace_suffix(@list_item_close_tag, @list_item_close_tag <> @unordered_list_close_tag) + String.replace( + html_line, + @list_item_open_tag, + @unordered_list_open_tag <> @list_item_open_tag, + global: false + ) + |> String.replace_suffix( + @list_item_close_tag, + @list_item_close_tag <> @unordered_list_close_tag + ) end end diff --git a/exercises/markdown/markdown.exs b/exercises/markdown/markdown.exs index dee8fe3540..7b2d19e38e 100644 --- a/exercises/markdown/markdown.exs +++ b/exercises/markdown/markdown.exs @@ -10,9 +10,9 @@ defmodule Markdown do iex> Markdown.parse("#Header!\n* __Bold Item__\n* _Italic Item_") "

Header!

" """ - @spec parse(String.t) :: String.t + @spec parse(String.t()) :: String.t() def parse(m) do - patch(Enum.join(Enum.map(String.split(m, "\n"), fn(t) -> process(t) end))) + patch(Enum.join(Enum.map(String.split(m, "\n"), fn t -> process(t) end))) end defp process(t) do @@ -46,7 +46,7 @@ defmodule Markdown do end defp join_words_with_tags(t) do - Enum.join(Enum.map(t, fn(w) -> replace_md_with_tag(w) end), " ") + Enum.join(Enum.map(t, fn w -> replace_md_with_tag(w) end), " ") end defp replace_md_with_tag(w) do @@ -70,6 +70,10 @@ defmodule Markdown do end defp patch(l) do - String.replace_suffix(String.replace(l, "
  • ", "") + String.replace_suffix( + String.replace(l, "
  • ", "" + ) end end diff --git a/exercises/markdown/markdown_test.exs b/exercises/markdown/markdown_test.exs index 48daff5025..ebeb1c0902 100644 --- a/exercises/markdown/markdown_test.exs +++ b/exercises/markdown/markdown_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("markdown.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule MarkdownTest do use ExUnit.Case @@ -67,7 +67,10 @@ defmodule MarkdownTest do @tag :pending test "with a little bit of everything" do input = "# Header!\n* __Bold Item__\n* _Italic Item_" - expected = "

    Header!

    " + + expected = + "

    Header!

    " + assert Markdown.parse(input) == expected end end diff --git a/exercises/matrix/example.exs b/exercises/matrix/example.exs index dfadb1e20e..4a936310ff 100644 --- a/exercises/matrix/example.exs +++ b/exercises/matrix/example.exs @@ -7,13 +7,14 @@ defmodule Matrix do """ @spec from_string(input :: String.t()) :: %Matrix{} def from_string(input) do - rows = input - |> String.split("\n", trim: true) - |> Enum.map(&parse_line/1) + rows = + input + |> String.split("\n", trim: true) + |> Enum.map(&parse_line/1) %Matrix{ matrix: rows, - transposed_matrix: rows |> List.zip |> Enum.map(&Tuple.to_list/1) + transposed_matrix: rows |> List.zip() |> Enum.map(&Tuple.to_list/1) } end @@ -28,7 +29,7 @@ defmodule Matrix do values separated by single spaces. """ @spec to_string(matrix :: %Matrix{}) :: String.t() - def to_string(%Matrix{ matrix: rows }) do + def to_string(%Matrix{matrix: rows}) do rows |> Enum.map(&join_row/1) |> Enum.join("\n") @@ -60,4 +61,3 @@ defmodule Matrix do @spec column(matrix :: %Matrix{}, index :: integer) :: list(integer) def column(%Matrix{transposed_matrix: cols}, index), do: Enum.at(cols, index) end - diff --git a/exercises/matrix/matrix.exs b/exercises/matrix/matrix.exs index e38132ca35..dc499c0a63 100644 --- a/exercises/matrix/matrix.exs +++ b/exercises/matrix/matrix.exs @@ -45,4 +45,3 @@ defmodule Matrix do def column(matrix, index) do end end - diff --git a/exercises/matrix/matrix_test.exs b/exercises/matrix/matrix_test.exs index 69f459c6d4..23ed0e62c1 100644 --- a/exercises/matrix/matrix_test.exs +++ b/exercises/matrix/matrix_test.exs @@ -2,15 +2,15 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("matrix.exs", __DIR__) end -ExUnit.start -ExUnit.configure trace: true, exclude: :pending +ExUnit.start() +ExUnit.configure(trace: true, exclude: :pending) defmodule MatrixTest do use ExUnit.Case @input "1 2 3\n4 5 6\n7 8 9" - #@tag :pending + # @tag :pending test "reading from and writing to string" do matrix = Matrix.from_string(@input) assert Matrix.to_string(matrix) == @input @@ -21,10 +21,10 @@ defmodule MatrixTest do matrix = Matrix.from_string(@input) assert Matrix.rows(matrix) == [ - [1, 2, 3], - [4, 5, 6], - [7, 8, 9] - ] + [1, 2, 3], + [4, 5, 6], + [7, 8, 9] + ] end @tag :pending @@ -41,10 +41,10 @@ defmodule MatrixTest do matrix = Matrix.from_string(@input) assert Matrix.columns(matrix) == [ - [1, 4, 7], - [2, 5, 8], - [3, 6, 9] - ] + [1, 4, 7], + [2, 5, 8], + [3, 6, 9] + ] end @tag :pending diff --git a/exercises/meetup/example.exs b/exercises/meetup/example.exs index fe86509f92..7a34781b3f 100644 --- a/exercises/meetup/example.exs +++ b/exercises/meetup/example.exs @@ -4,8 +4,13 @@ defmodule Meetup do """ @type weekday :: - :monday | :tuesday | :wednesday - | :thursday | :friday | :saturday | :sunday + :monday + | :tuesday + | :wednesday + | :thursday + | :friday + | :saturday + | :sunday @type schedule :: :first | :second | :third | :fourth | :last | :teenth @@ -15,37 +20,39 @@ defmodule Meetup do The schedule is in which week (1..4, last or "teenth") the meetup date should fall. """ - @spec meetup(pos_integer, pos_integer, weekday, schedule) :: :calendar.date + @spec meetup(pos_integer, pos_integer, weekday, schedule) :: :calendar.date() def meetup(year, month, weekday, :last) do start_day = :calendar.last_day_of_the_month(year, month) - 6 meetup_nth(year, month, start_day, weekday) end + def meetup(year, month, weekday, schedule) do meetup_nth(year, month, schedule_start(schedule), weekday) end defp meetup_nth(year, month, start_day, weekday) do w = weekday_num(weekday) + case w - :calendar.day_of_the_week(year, month, start_day) do - n when n < 0 -> {year, month, start_day + n + 7} - n -> {year, month, start_day + n} + n when n < 0 -> {year, month, start_day + n + 7} + n -> {year, month, start_day + n} end end # Aliases for the day of week numbers from Erlang. # # Case matching is used because that's very fast in Elixir/Erlang. - defp weekday_num(:monday), do: 1 - defp weekday_num(:tuesday), do: 2 + defp weekday_num(:monday), do: 1 + defp weekday_num(:tuesday), do: 2 defp weekday_num(:wednesday), do: 3 - defp weekday_num(:thursday), do: 4 - defp weekday_num(:friday), do: 5 - defp weekday_num(:saturday), do: 6 - defp weekday_num(:sunday), do: 7 + defp weekday_num(:thursday), do: 4 + defp weekday_num(:friday), do: 5 + defp weekday_num(:saturday), do: 6 + defp weekday_num(:sunday), do: 7 - defp schedule_start(:first), do: 1 + defp schedule_start(:first), do: 1 defp schedule_start(:second), do: 8 - defp schedule_start(:third), do: 15 + defp schedule_start(:third), do: 15 defp schedule_start(:fourth), do: 22 defp schedule_start(:teenth), do: 13 end diff --git a/exercises/meetup/meetup.exs b/exercises/meetup/meetup.exs index a0daec8212..9592a98459 100644 --- a/exercises/meetup/meetup.exs +++ b/exercises/meetup/meetup.exs @@ -4,8 +4,13 @@ defmodule Meetup do """ @type weekday :: - :monday | :tuesday | :wednesday - | :thursday | :friday | :saturday | :sunday + :monday + | :tuesday + | :wednesday + | :thursday + | :friday + | :saturday + | :sunday @type schedule :: :first | :second | :third | :fourth | :last | :teenth @@ -15,8 +20,7 @@ defmodule Meetup do The schedule is in which week (1..4, last or "teenth") the meetup date should fall. """ - @spec meetup(pos_integer, pos_integer, weekday, schedule) :: :calendar.date + @spec meetup(pos_integer, pos_integer, weekday, schedule) :: :calendar.date() def meetup(year, month, weekday, schedule) do - end end diff --git a/exercises/meetup/meetup_test.exs b/exercises/meetup/meetup_test.exs index e5b1fafe71..adba26434e 100644 --- a/exercises/meetup/meetup_test.exs +++ b/exercises/meetup/meetup_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("meetup.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule MeetupTest do use ExUnit.Case diff --git a/exercises/minesweeper/minesweeper.exs b/exercises/minesweeper/minesweeper.exs index 4a7c2262ba..1b5aad99d4 100644 --- a/exercises/minesweeper/minesweeper.exs +++ b/exercises/minesweeper/minesweeper.exs @@ -1,11 +1,9 @@ defmodule Minesweeper do - @doc """ Annotate empty spots next to mines with the number of mines next to them. """ - @spec annotate([String.t]) :: [String.t] + @spec annotate([String.t()]) :: [String.t()] def annotate(board) do - end end diff --git a/exercises/minesweeper/minesweeper_test.exs b/exercises/minesweeper/minesweeper_test.exs index 1eacf86007..45fef21a78 100644 --- a/exercises/minesweeper/minesweeper_test.exs +++ b/exercises/minesweeper/minesweeper_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("minesweeper.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule MinesweeperTest do use ExUnit.Case @@ -18,25 +18,19 @@ defmodule MinesweeperTest do @tag :pending test "empty board" do - b = [" ", - " ", - " "] + b = [" ", " ", " "] assert Minesweeper.annotate(clean(b)) == b end @tag :pending test "board full of mines" do - b = ["***", - "***", - "***"] + b = ["***", "***", "***"] assert Minesweeper.annotate(clean(b)) == b end @tag :pending test "surrounded" do - b = ["***", - "*8*", - "***"] + b = ["***", "*8*", "***"] assert Minesweeper.annotate(clean(b)) == b end @@ -48,21 +42,13 @@ defmodule MinesweeperTest do @tag :pending test "vertical line" do - b = ["1", - "*", - "2", - "*", - "1"] + b = ["1", "*", "2", "*", "1"] assert Minesweeper.annotate(clean(b)) == b end @tag :pending test "cross" do - b = [" 2*2 ", - "25*52", - "*****", - "25*52", - " 2*2 "] + b = [" 2*2 ", "25*52", "*****", "25*52", " 2*2 "] assert Minesweeper.annotate(clean(b)) == b end end diff --git a/exercises/nth-prime/example.exs b/exercises/nth-prime/example.exs index ca2f9cb690..3b09d1d931 100644 --- a/exercises/nth-prime/example.exs +++ b/exercises/nth-prime/example.exs @@ -1,16 +1,16 @@ defmodule Prime do - @doc """ Generates the nth prime. """ @spec nth(non_neg_integer) :: non_neg_integer def nth(count) do - if count < 1, do: raise ArgumentError + if count < 1, do: raise(ArgumentError) nth(count, 1000) end defp nth(count, max) do primes = primes_to(max) + cond do Enum.count(primes) < count -> nth(count, max * 4) true -> Enum.at(primes, count - 1) @@ -18,13 +18,13 @@ defmodule Prime do end defp primes_to(limit) do - Enum.reduce(2..limit, [], fn(number, primes) -> - if is_prime?(number, primes), do: [number|primes], else: primes end) - |> Enum.reverse + Enum.reduce(2..limit, [], fn number, primes -> + if is_prime?(number, primes), do: [number | primes], else: primes + end) + |> Enum.reverse() end defp is_prime?(number, primes) do Enum.all?(primes, &(rem(number, &1) != 0)) end - -end \ No newline at end of file +end diff --git a/exercises/nth-prime/nth_prime.exs b/exercises/nth-prime/nth_prime.exs index b2c253baf1..eab7c4faca 100644 --- a/exercises/nth-prime/nth_prime.exs +++ b/exercises/nth-prime/nth_prime.exs @@ -1,5 +1,4 @@ defmodule Prime do - @doc """ Generates the nth prime. """ diff --git a/exercises/nth-prime/nth_prime_test.exs b/exercises/nth-prime/nth_prime_test.exs index 816c57b6b8..daff5f3ef9 100644 --- a/exercises/nth-prime/nth_prime_test.exs +++ b/exercises/nth-prime/nth_prime_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("nth_prime.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule NthPrimeTest do use ExUnit.Case @@ -30,6 +30,6 @@ defmodule NthPrimeTest do @tag :pending test "weird case" do - catch_error Prime.nth(0) + catch_error(Prime.nth(0)) end end diff --git a/exercises/nucleotide-count/example.exs b/exercises/nucleotide-count/example.exs index 960905f32f..c383fcfc45 100644 --- a/exercises/nucleotide-count/example.exs +++ b/exercises/nucleotide-count/example.exs @@ -13,10 +13,11 @@ defmodule NucleotideCount do 1 """ - def count(strand, nucleotide) when nucleotide in(@nucleotides) do - Enum.count strand, &(&1 == nucleotide) + def count(strand, nucleotide) when nucleotide in @nucleotides do + Enum.count(strand, &(&1 == nucleotide)) end - def count(_strand, _nucleotide), do: raise ArgumentError + + def count(_strand, _nucleotide), do: raise(ArgumentError) @doc """ Returns a summary of counts by nucleotide. diff --git a/exercises/nucleotide-count/nucleotide_count.exs b/exercises/nucleotide-count/nucleotide_count.exs index 5ea034142f..ecad9cc77f 100644 --- a/exercises/nucleotide-count/nucleotide_count.exs +++ b/exercises/nucleotide-count/nucleotide_count.exs @@ -14,10 +14,8 @@ defmodule NucleotideCount do """ @spec count([char], char) :: non_neg_integer def count(strand, nucleotide) do - end - @doc """ Returns a summary of counts by nucleotide. @@ -28,6 +26,5 @@ defmodule NucleotideCount do """ @spec histogram([char]) :: map def histogram(strand) do - end end diff --git a/exercises/nucleotide-count/nucleotide_count_test.exs b/exercises/nucleotide-count/nucleotide_count_test.exs index dc6d9b05d9..c144c180cc 100644 --- a/exercises/nucleotide-count/nucleotide_count_test.exs +++ b/exercises/nucleotide-count/nucleotide_count_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("nucleotide_count.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule NucleotideCountTest do use ExUnit.Case diff --git a/exercises/ocr-numbers/example.exs b/exercises/ocr-numbers/example.exs index 2a7c368611..8ea1cfa739 100644 --- a/exercises/ocr-numbers/example.exs +++ b/exercises/ocr-numbers/example.exs @@ -1,10 +1,9 @@ defmodule OCRNumbers do - @doc """ Given a 3 x 4 grid of pipes, underscores, and spaces, determine which number is represented, or whether it is garbled. """ - @spec convert([String.t]) :: String.t + @spec convert([String.t()]) :: String.t() def convert(input) do Enum.chunk(input, 4) |> Enum.map(fn row_set -> _convert(row_set, "") end) @@ -21,9 +20,10 @@ defmodule OCRNumbers do def _convert(_, {:error, _} = error), do: error def _convert(input, _) when length(input) != 4, do: {:error, 'invalid line count'} def _convert(["", "", "", ""], output), do: output + def _convert(input, output) do split_strings = Enum.map(input, fn a -> String.split_at(a, 3) end) - this_character = Enum.map(split_strings, fn ({a, _}) -> a end) + this_character = Enum.map(split_strings, fn {a, _} -> a end) other_characters = Enum.map(split_strings, fn {_, a} -> a end) lengths = Enum.map(this_character, fn a -> String.length(a) end) diff --git a/exercises/ocr-numbers/ocr_numbers.exs b/exercises/ocr-numbers/ocr_numbers.exs index 30f9f6bf02..34542a1baf 100644 --- a/exercises/ocr-numbers/ocr_numbers.exs +++ b/exercises/ocr-numbers/ocr_numbers.exs @@ -1,10 +1,9 @@ defmodule OCRNumbers do - @doc """ Given a 3 x 4 grid of pipes, underscores, and spaces, determine which number is represented, or whether it is garbled. """ - @spec convert([String.t]) :: String.t + @spec convert([String.t()]) :: String.t() def convert(input) do end end diff --git a/exercises/ocr-numbers/ocr_numbers_test.exs b/exercises/ocr-numbers/ocr_numbers_test.exs index c5bbda583a..fc71e5403d 100644 --- a/exercises/ocr-numbers/ocr_numbers_test.exs +++ b/exercises/ocr-numbers/ocr_numbers_test.exs @@ -2,238 +2,223 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("ocr_numbers.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule OCRNumbersTest do use ExUnit.Case # @tag :pending test "Recognizes 0" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ ", "| |", "|_|", " " - ] - ) + ]) + assert number == {:ok, "0"} end @tag :pending test "Recognizes 1" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " ", " |", " |", " " - ] - ) + ]) assert number == {:ok, "1"} end @tag :pending test "Unreadable but correctly sized inputs return ?" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " ", " _", " |", " " - ] - ) + ]) assert number == {:ok, "?"} end @tag :pending test "Input with a number of lines that is not a multiple of four raises an error" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ ", "| |", " " - ] - ) + ]) assert number == {:error, 'invalid line count'} end @tag :pending test "Input with a number of columns that is not a multiple of three raises an error" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " ", " |", " |", " " - ] - ) + ]) assert number == {:error, 'invalid column count'} end @tag :pending test "Recognizes 110101100" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ _ _ _ ", " | || | || | | || || |", " | ||_| ||_| | ||_||_|", " " - ] - ) + ]) assert number == {:ok, "110101100"} end @tag :pending test "Garbled numbers in a string are replaced with ?" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ _ _ ", " | || | || | || || |", " | | _| ||_| | ||_||_|", " " - ] - ) + ]) assert number == {:ok, "11?10?1?0"} end @tag :pending test "Recognizes 2" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ ", " _|", "|_ ", " " - ] - ) + ]) assert number == {:ok, "2"} end @tag :pending test "Recognizes 3" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ ", " _|", " _|", " " - ] - ) + ]) assert number == {:ok, "3"} end @tag :pending test "Recognizes 4" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " ", "|_|", " |", " " - ] - ) + ]) assert number == {:ok, "4"} end @tag :pending test "Recognizes 5" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ ", "|_ ", " _|", " " - ] - ) + ]) assert number == {:ok, "5"} end @tag :pending test "Recognizes 6" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ ", "|_ ", "|_|", " " - ] - ) + ]) assert number == {:ok, "6"} end @tag :pending test "Regonizes 7" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ ", " |", " |", " " - ] - ) + ]) assert number == {:ok, "7"} end @tag :pending test "Recognizes 8" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ ", "|_|", "|_|", " " - ] - ) + ]) assert number == {:ok, "8"} end @tag :pending test "Recognizes 9" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ ", "|_|", " _|", " " - ] - ) + ]) assert number == {:ok, "9"} end @tag :pending test "Recognizes string of decimal numbers" do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ _ _ _ _ _ _ _ ", " | _| _||_||_ |_ ||_||_|| |", " ||_ _| | _||_| ||_| _||_|", " " - ] - ) + ]) assert number == {:ok, "1234567890"} end @tag :pending test "Numbers separated by empty lines are recognized. Lines are joined by commas." do - number = OCRNumbers.convert( - [ + number = + OCRNumbers.convert([ " _ _ ", " | _| _|", " ||_ _|", @@ -246,8 +231,7 @@ defmodule OCRNumbersTest do " ||_||_|", " ||_| _|", " " - ] - ) + ]) assert number == {:ok, "123,456,789"} end diff --git a/exercises/palindrome-products/example.exs b/exercises/palindrome-products/example.exs index 994d6a5d78..412ebb2508 100644 --- a/exercises/palindrome-products/example.exs +++ b/exercises/palindrome-products/example.exs @@ -1,13 +1,12 @@ defmodule Palindromes do - @doc """ Generates all palindrome products from an optionally given min factor (or 1) to a given max factor. """ @spec generate(non_neg_integer) :: map @spec generate(non_neg_integer, non_neg_integer) :: map def generate(max_factor, min_factor \\ 1) do - Enum.reduce(min_factor..max_factor, %{}, fn(x, map) -> - Enum.reduce(x..max_factor, map, fn(y, products) -> + Enum.reduce(min_factor..max_factor, %{}, fn x, map -> + Enum.reduce(x..max_factor, map, fn y, products -> if palindrome?(x * y), do: add_factor(products, x, y), else: products end) end) @@ -19,8 +18,6 @@ defmodule Palindromes do defp add_factor(map, x, y) do product = x * y - Map.update(map, product, - [[x, y]], fn(val) -> Enum.concat(val, [[x, y]]) end) + Map.update(map, product, [[x, y]], fn val -> Enum.concat(val, [[x, y]]) end) end - end diff --git a/exercises/palindrome-products/palindrome_products.exs b/exercises/palindrome-products/palindrome_products.exs index 4c09259eea..8fa2e945d0 100644 --- a/exercises/palindrome-products/palindrome_products.exs +++ b/exercises/palindrome-products/palindrome_products.exs @@ -1,5 +1,4 @@ defmodule Palindromes do - @doc """ Generates all palindrome products from an optionally given min factor (or 1) to a given max factor. """ diff --git a/exercises/palindrome-products/palindrome_products_test.exs b/exercises/palindrome-products/palindrome_products_test.exs index 3fe819357f..072c504318 100644 --- a/exercises/palindrome-products/palindrome_products_test.exs +++ b/exercises/palindrome-products/palindrome_products_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("palindrome_products.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule PalindromeProductsTest do use ExUnit.Case @@ -11,35 +11,35 @@ defmodule PalindromeProductsTest do # @tag :pending test "largest palindrome from single digit factors" do palindromes = Palindromes.generate(9) - assert (palindromes |> Map.keys |> Enum.sort |> List.last) == 9 + assert palindromes |> Map.keys() |> Enum.sort() |> List.last() == 9 assert Enum.sort(palindromes[9]) == [[1, 9], [3, 3]] end @tag :pending test "largest palindrome from double digit factors" do palindromes = Palindromes.generate(99, 10) - assert (palindromes |> Map.keys |> Enum.sort |> List.last) == 9009 + assert palindromes |> Map.keys() |> Enum.sort() |> List.last() == 9009 assert palindromes[9009] == [[91, 99]] end @tag :pending test "smallest palindrome from double digit factors" do palindromes = Palindromes.generate(99, 10) - assert (palindromes |> Map.keys |> Enum.sort |> hd) == 121 + assert palindromes |> Map.keys() |> Enum.sort() |> hd == 121 assert palindromes[121] == [[11, 11]] end @tag :pending test "largest palindrome from triple digit factors" do palindromes = Palindromes.generate(999, 100) - assert (palindromes |> Map.keys |> Enum.sort |> List.last) == 906609 - assert palindromes[906609] == [[913, 993]] + assert palindromes |> Map.keys() |> Enum.sort() |> List.last() == 906_609 + assert palindromes[906_609] == [[913, 993]] end @tag :pending test "smallest palindromes from triple digit factors" do palindromes = Palindromes.generate(999, 100) - assert (palindromes |> Map.keys |> Enum.sort |> hd) == 10201 + assert palindromes |> Map.keys() |> Enum.sort() |> hd == 10201 assert palindromes[10201] == [[101, 101]] end end diff --git a/exercises/pangram/pangram.exs b/exercises/pangram/pangram.exs index 5f16ca125f..20fb44200a 100644 --- a/exercises/pangram/pangram.exs +++ b/exercises/pangram/pangram.exs @@ -12,7 +12,7 @@ defmodule Pangram do """ - @spec pangram?(String.t) :: boolean + @spec pangram?(String.t()) :: boolean def pangram?(sentence) do end end diff --git a/exercises/pangram/pangram_test.exs b/exercises/pangram/pangram_test.exs index bb955cd713..d5ced68810 100644 --- a/exercises/pangram/pangram_test.exs +++ b/exercises/pangram/pangram_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("pangram.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule PangramTest do use ExUnit.Case @@ -55,6 +55,8 @@ defmodule PangramTest do @tag :pending test "pangram in alphabet other than ASCII" do - refute Pangram.pangram?("Широкая электрификация южных губерний даст мощный толчок подъёму сельского хозяйства.") + refute Pangram.pangram?( + "Широкая электрификация южных губерний даст мощный толчок подъёму сельского хозяйства." + ) end end diff --git a/exercises/parallel-letter-frequency/example.exs b/exercises/parallel-letter-frequency/example.exs index 01339ab36a..4875c18e40 100644 --- a/exercises/parallel-letter-frequency/example.exs +++ b/exercises/parallel-letter-frequency/example.exs @@ -5,9 +5,9 @@ defmodule Frequency do Returns a map of characters to frequencies. """ def frequency(texts, workers) do - groups = Enum.map(0..(workers-1), &stripe(&1, texts, workers)) + groups = Enum.map(0..(workers - 1), &stripe(&1, texts, workers)) + # :rpc.pmap({Frequency, :count_texts}, [], groups) Enum.map(groups, &Frequency.count_texts/1) - #:rpc.pmap({Frequency, :count_texts}, [], groups) |> merge_freqs() end @@ -25,17 +25,19 @@ defmodule Frequency do defp count_text(string) do String.downcase(string) |> String.graphemes() + # At the time of writing Elixir doesn't yet have a way to determine if a # character is a letter. So use a workaround with Regex. - String.replace(string, ~r/\P{L}+/u, "") # \P{L} = anything but a letter + # \P{L} = anything but a letter + String.replace(string, ~r/\P{L}+/u, "") |> String.downcase() |> String.graphemes() - |> Enum.reduce(%{}, fn c, acc -> Map.update(acc, c, 1, &(&1+1)) end) + |> Enum.reduce(%{}, fn c, acc -> Map.update(acc, c, 1, &(&1 + 1)) end) end defp merge_freqs(map) do Enum.reduce(map, %{}, fn d, acc -> - Map.merge(acc, d, fn _, a, b -> a+b end) + Map.merge(acc, d, fn _, a, b -> a + b end) end) end end diff --git a/exercises/parallel-letter-frequency/frequency.exs b/exercises/parallel-letter-frequency/frequency.exs index 5a23bfa6ec..39d7b46e88 100644 --- a/exercises/parallel-letter-frequency/frequency.exs +++ b/exercises/parallel-letter-frequency/frequency.exs @@ -6,8 +6,7 @@ defmodule Frequency do The number of worker processes to use can be set with 'workers'. """ - @spec frequency([String.t], pos_integer) :: map + @spec frequency([String.t()], pos_integer) :: map def frequency(texts, workers) do - end end diff --git a/exercises/parallel-letter-frequency/parallel_letter_frequency_test.exs b/exercises/parallel-letter-frequency/parallel_letter_frequency_test.exs index 37f56c607d..0813cc69c1 100644 --- a/exercises/parallel-letter-frequency/parallel_letter_frequency_test.exs +++ b/exercises/parallel-letter-frequency/parallel_letter_frequency_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("frequency.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) # Your code should contain a frequency(texts, workers) function which accepts a # list of texts and the number of workers to use in parallel. @@ -76,8 +76,7 @@ defmodule FrequencyTest do @tag :pending test "many times the same text gives a predictable result" do - assert freq(List.duplicate("abc", 1000)) - == %{"a" => 1000, "b" => 1000, "c" => 1000} + assert freq(List.duplicate("abc", 1000)) == %{"a" => 1000, "b" => 1000, "c" => 1000} end @tag :pending diff --git a/exercises/pascals-triangle/example.exs b/exercises/pascals-triangle/example.exs index 730e6e2165..1154609efb 100644 --- a/exercises/pascals-triangle/example.exs +++ b/exercises/pascals-triangle/example.exs @@ -8,7 +8,8 @@ defmodule PascalsTriangle do do_rows(num - 1, [[1]]) end - defp do_rows(0, rows), do: Enum.reverse rows + defp do_rows(0, rows), do: Enum.reverse(rows) + defp do_rows(n, rows = [h | _]) do do_rows(n - 1, [next_row(h) | rows]) end diff --git a/exercises/pascals-triangle/pascals_triangle_test.exs b/exercises/pascals-triangle/pascals_triangle_test.exs index b94162add4..a80a7b78a2 100644 --- a/exercises/pascals-triangle/pascals_triangle_test.exs +++ b/exercises/pascals-triangle/pascals_triangle_test.exs @@ -2,9 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("pascals_triangle.exs", __DIR__) end - -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule PascalsTriangleTest do use ExUnit.Case @@ -26,20 +25,39 @@ defmodule PascalsTriangleTest do @tag :pending test "fourth row" do - assert List.last(PascalsTriangle.rows(4)) == [1, 3, 3, 1] + assert List.last(PascalsTriangle.rows(4)) == [1, 3, 3, 1] end @tag :pending test "fifth row" do - assert List.last(PascalsTriangle.rows(5)) == [1, 4, 6, 4, 1] + assert List.last(PascalsTriangle.rows(5)) == [1, 4, 6, 4, 1] end @tag :pending test "twentieth row" do expected = [ - 1, 19, 171, 969, 3876, 11_628, 27_132, 50_388, 75_582, 92_378, 92_378, - 75_582, 50_388, 27_132, 11_628, 3876, 969, 171, 19, 1 + 1, + 19, + 171, + 969, + 3876, + 11_628, + 27_132, + 50_388, + 75_582, + 92_378, + 92_378, + 75_582, + 50_388, + 27_132, + 11_628, + 3876, + 969, + 171, + 19, + 1 ] - assert List.last(PascalsTriangle.rows(20)) == expected + + assert List.last(PascalsTriangle.rows(20)) == expected end end diff --git a/exercises/perfect-numbers/example.exs b/exercises/perfect-numbers/example.exs index 3994ae3126..0503e7e4e0 100644 --- a/exercises/perfect-numbers/example.exs +++ b/exercises/perfect-numbers/example.exs @@ -9,10 +9,12 @@ defmodule PerfectNumbers do :abundant if the aliquot sum is greater than `number` :deficient if the aliquot sum is less than `number` """ - @spec classify(number :: integer) :: ({ :ok, atom } | { :error, String.t() }) - def classify(number) when number < 1, do: { :error, "Classification is only possible for natural numbers." } + @spec classify(number :: integer) :: {:ok, atom} | {:error, String.t()} + def classify(number) when number < 1, + do: {:error, "Classification is only possible for natural numbers."} + def classify(number) do - { :ok, number |> aliquot_sum |> do_classify(number) } + {:ok, number |> aliquot_sum |> do_classify(number)} end defp do_classify(aliquot, aliquot), do: :perfect @@ -23,12 +25,12 @@ defmodule PerfectNumbers do number |> factors |> Enum.reject(&(&1 == number)) - |> Enum.sum + |> Enum.sum() end defp factors(number), do: factors(number, div(number, 2)) defp factors(1, _), do: [1] defp factors(_, 1), do: [1] - defp factors(number, i) when rem(number, i) == 0, do: [i | factors(number, i-1)] - defp factors(number, i), do: factors(number, i-1) + defp factors(number, i) when rem(number, i) == 0, do: [i | factors(number, i - 1)] + defp factors(number, i), do: factors(number, i - 1) end diff --git a/exercises/perfect-numbers/perfect_numbers.exs b/exercises/perfect-numbers/perfect_numbers.exs index 54105fa647..12d3bf4bbc 100644 --- a/exercises/perfect-numbers/perfect_numbers.exs +++ b/exercises/perfect-numbers/perfect_numbers.exs @@ -9,8 +9,7 @@ defmodule PerfectNumbers do :abundant if the aliquot sum is greater than `number` :deficient if the aliquot sum is less than `number` """ - @spec classify(number :: integer) :: ({ :ok, atom } | { :error, String.t() }) + @spec classify(number :: integer) :: {:ok, atom} | {:error, String.t()} def classify(number) do end end - diff --git a/exercises/perfect-numbers/perfect_numbers_test.exs b/exercises/perfect-numbers/perfect_numbers_test.exs index de7b8dafb9..6a3a1e7301 100644 --- a/exercises/perfect-numbers/perfect_numbers_test.exs +++ b/exercises/perfect-numbers/perfect_numbers_test.exs @@ -2,83 +2,84 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("perfect_numbers.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule PerfectNumbersTest do use ExUnit.Case describe "Perfect numbers" do - #@tag :pending + # @tag :pending test "Smallest perfect number is classified correctly" do - assert PerfectNumbers.classify(6) == { :ok, :perfect } + assert PerfectNumbers.classify(6) == {:ok, :perfect} end @tag :pending test "Medium perfect number is classified correctly" do - assert PerfectNumbers.classify(28) == { :ok, :perfect } + assert PerfectNumbers.classify(28) == {:ok, :perfect} end @tag :pending test "Large perfect number is classified correctly" do - assert PerfectNumbers.classify(33550336) == { :ok, :perfect } + assert PerfectNumbers.classify(33_550_336) == {:ok, :perfect} end end describe "Abundant numbers" do @tag :pending test "Smallest abundant number is classified correctly" do - assert PerfectNumbers.classify(12) == { :ok, :abundant } + assert PerfectNumbers.classify(12) == {:ok, :abundant} end @tag :pending test "Medium abundant number is classified correctly" do - assert PerfectNumbers.classify(30) == { :ok, :abundant } + assert PerfectNumbers.classify(30) == {:ok, :abundant} end @tag :pending test "Large abundant number is classified correctly" do - assert PerfectNumbers.classify(33550335) == { :ok, :abundant } + assert PerfectNumbers.classify(33_550_335) == {:ok, :abundant} end end describe "Deficient numbers" do @tag :pending test "Smallest prime deficient number is classified correctly" do - assert PerfectNumbers.classify(2) == { :ok, :deficient } + assert PerfectNumbers.classify(2) == {:ok, :deficient} end @tag :pending test "Smallest non-prime deficient number is classified correctly" do - assert PerfectNumbers.classify(4) == { :ok, :deficient } + assert PerfectNumbers.classify(4) == {:ok, :deficient} end @tag :pending test "Medium deficient number is classified correctly" do - assert PerfectNumbers.classify(32) == { :ok, :deficient } + assert PerfectNumbers.classify(32) == {:ok, :deficient} end @tag :pending test "Large deficient number is classified correctly" do - assert PerfectNumbers.classify(33550337) == { :ok, :deficient } + assert PerfectNumbers.classify(33_550_337) == {:ok, :deficient} end @tag :pending test "Edge case (no factors other than itself) is classified correctly" do - assert PerfectNumbers.classify(1) == { :ok, :deficient } + assert PerfectNumbers.classify(1) == {:ok, :deficient} end end describe "Invalid inputs" do @tag :pending test "Zero is rejected (not a natural number)" do - assert PerfectNumbers.classify(0) == { :error, "Classification is only possible for natural numbers." } + assert PerfectNumbers.classify(0) == + {:error, "Classification is only possible for natural numbers."} end @tag :pending test "Negative integer is rejected (not a natural number)" do - assert PerfectNumbers.classify(-1) == { :error, "Classification is only possible for natural numbers." } + assert PerfectNumbers.classify(-1) == + {:error, "Classification is only possible for natural numbers."} end end end - diff --git a/exercises/phone-number/example.exs b/exercises/phone-number/example.exs index 3aebc227e3..476ed2dcc6 100644 --- a/exercises/phone-number/example.exs +++ b/exercises/phone-number/example.exs @@ -27,17 +27,24 @@ defmodule Phone do iex> Phone.number("867.5309") "0000000000" """ - @spec number(String.t) :: String.t + @spec number(String.t()) :: String.t() def number(raw) do + # remove decorations raw - |> String.replace(~r/[\s+.()-]/, "") # remove decorations + |> String.replace(~r/[\s+.()-]/, "") |> valid? - |> (fn false -> @invalid; num -> String.replace(num, ~r/^1/, "") end).() + |> (fn + false -> @invalid + num -> String.replace(num, ~r/^1/, "") + end).() end defp valid?(num) do Regex.match?(~r/^1?(?:[2-9][0-9]{2}){2}\d{4}$/, num) - |> (fn true -> num; false -> false end).() + |> (fn + true -> num + false -> false + end).() end @doc """ @@ -60,11 +67,12 @@ defmodule Phone do iex> Phone.area_code("867.5309") "000" """ - @spec area_code(String.t) :: String.t + @spec area_code(String.t()) :: String.t() def area_code(raw) do + # the first three digits are area_code raw - |> __MODULE__.number - |> String.slice(0, 3) # the first three digits are area_code + |> __MODULE__.number() + |> String.slice(0, 3) end @doc """ @@ -87,12 +95,12 @@ defmodule Phone do iex> Phone.pretty("867.5309") "(000) 000-0000" """ - @spec pretty(String.t) :: String.t + @spec pretty(String.t()) :: String.t() def pretty(raw) do raw - |> __MODULE__.number + |> __MODULE__.number() |> (fn <> -> - "(#{area_code}) #{exchange_code}-#{rest}" - end).() + "(#{area_code}) #{exchange_code}-#{rest}" + end).() end end diff --git a/exercises/phone-number/phone_number.exs b/exercises/phone-number/phone_number.exs index 3d52ea65c2..1ec6425c16 100644 --- a/exercises/phone-number/phone_number.exs +++ b/exercises/phone-number/phone_number.exs @@ -22,7 +22,7 @@ defmodule Phone do iex> Phone.number("867.5309") "0000000000" """ - @spec number(String.t) :: String.t + @spec number(String.t()) :: String.t() def number(raw) do end @@ -46,7 +46,7 @@ defmodule Phone do iex> Phone.area_code("867.5309") "000" """ - @spec area_code(String.t) :: String.t + @spec area_code(String.t()) :: String.t() def area_code(raw) do end @@ -70,7 +70,7 @@ defmodule Phone do iex> Phone.pretty("867.5309") "(000) 000-0000" """ - @spec pretty(String.t) :: String.t + @spec pretty(String.t()) :: String.t() def pretty(raw) do end end diff --git a/exercises/phone-number/phone_number_test.exs b/exercises/phone-number/phone_number_test.exs index 5dc831bbfd..8c0b3d0ee6 100644 --- a/exercises/phone-number/phone_number_test.exs +++ b/exercises/phone-number/phone_number_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("phone_number.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule PhoneTest do use ExUnit.Case diff --git a/exercises/pig-latin/pig_latin.exs b/exercises/pig-latin/pig_latin.exs index 159b380734..e5e67b0caa 100644 --- a/exercises/pig-latin/pig_latin.exs +++ b/exercises/pig-latin/pig_latin.exs @@ -17,4 +17,3 @@ defmodule PigLatin do def translate(phrase) do end end - diff --git a/exercises/pig-latin/pig_latin_test.exs b/exercises/pig-latin/pig_latin_test.exs index 9034c528d2..cab9bacce0 100644 --- a/exercises/pig-latin/pig_latin_test.exs +++ b/exercises/pig-latin/pig_latin_test.exs @@ -2,14 +2,14 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("pig_latin.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule PigLatinTest do use ExUnit.Case describe "ay is added to words that start with vowels" do - #@tag :pending + # @tag :pending test "word beginning with a" do assert PigLatin.translate("apple") == "appleay" end diff --git a/exercises/poker/example.exs b/exercises/poker/example.exs index 9aa9cfb63e..8e17d77ede 100644 --- a/exercises/poker/example.exs +++ b/exercises/poker/example.exs @@ -29,9 +29,10 @@ defmodule Poker do """ @spec best_hand(list(list(String.t()))) :: list(list(String.t())) def best_hand(hands) do - sorted_hands = hands - |> Enum.map(&score_hand/1) - |> Enum.sort(&sort_scored_hands/2) + sorted_hands = + hands + |> Enum.map(&score_hand/1) + |> Enum.sort(&sort_scored_hands/2) [{_, highest_score, highest_extra} | _] = sorted_hands @@ -47,19 +48,21 @@ defmodule Poker do @suits ~w(clubs diamonds hearts spades)a @scores ~w(straight_flush four_of_a_kind full_house flush straight three_of_a_kind two_pair pair high_card)a - for {rank, value} <- Enum.with_index(@ranks, 2), suit <- @suits do - suit_char = suit |> to_string |> String.upcase |> String.first + for {rank, value} <- Enum.with_index(@ranks, 2), + suit <- @suits do + suit_char = suit |> to_string |> String.upcase() |> String.first() - defp card(<< unquote(rank), unquote(suit_char) >>), do: {unquote(value), unquote(suit)} + defp card(<>), do: {unquote(value), unquote(suit)} end defp score_hand(hand) do - {ranks, suits} = hand - |> Enum.map(&card/1) - |> Enum.sort(&sort_rank_asc/2) - |> Enum.unzip + {ranks, suits} = + hand + |> Enum.map(&card/1) + |> Enum.sort(&sort_rank_asc/2) + |> Enum.unzip() - flush = suits |> Enum.uniq |> length |> Kernel.==(1) + flush = suits |> Enum.uniq() |> length |> Kernel.==(1) ranks |> Enum.group_by(fn x -> x end) @@ -71,41 +74,70 @@ defmodule Poker do defp score_hand(_, [2, 3, 4, 5, 14], true), do: {:straight_flush, {5}} defp score_hand(_, [2, 3, 4, 5, 14], _), do: {:straight, {5}} - defp score_hand(counts, [low, _, _, _, high], true) when length(counts) == 5 and high-low == 4, do: {:straight_flush, {high}} - defp score_hand(counts, [low, _, _, _, high], _) when length(counts) == 5 and high-low == 4, do: {:straight, {high}} - defp score_hand(_, ranks, true), do: {:flush, {ranks |> Enum.sort |> Enum.reverse}} + + defp score_hand(counts, [low, _, _, _, high], true) when length(counts) == 5 and high - low == 4, + do: {:straight_flush, {high}} + + defp score_hand(counts, [low, _, _, _, high], _) when length(counts) == 5 and high - low == 4, + do: {:straight, {high}} + + defp score_hand(_, ranks, true), do: {:flush, {ranks |> Enum.sort() |> Enum.reverse()}} defp score_hand([{kicker, 1}, {high, 4}], _, _), do: {:four_of_a_kind, {high, kicker}} defp score_hand([{pair, 2}, {triplet, 3}], _, _), do: {:full_house, {triplet, pair}} - defp score_hand([{kicker1, 1}, {kicker2, 1}, {triplet, 3}], _, _), do: {:three_of_a_kind, {triplet, [ kicker1, kicker2 ] |> Enum.sort |> Enum.reverse}} - defp score_hand([{kicker, 1}, {low_pair, 2}, {high_pair, 2}], _, _), do: {:two_pair, {high_pair, low_pair, kicker}} - defp score_hand([{kicker1, 1}, {kicker2, 1}, {kicker3, 1}, {pair, 2}], _, _), do: {:pair, {pair, [ kicker1, kicker2, kicker3 ] |> Enum.sort |> Enum.reverse}} - defp score_hand(_, ranks, _), do: {:high_card, {ranks |> Enum.sort |> Enum.reverse}} + + defp score_hand([{kicker1, 1}, {kicker2, 1}, {triplet, 3}], _, _), + do: {:three_of_a_kind, {triplet, [kicker1, kicker2] |> Enum.sort() |> Enum.reverse()}} + + defp score_hand([{kicker, 1}, {low_pair, 2}, {high_pair, 2}], _, _), + do: {:two_pair, {high_pair, low_pair, kicker}} + + defp score_hand([{kicker1, 1}, {kicker2, 1}, {kicker3, 1}, {pair, 2}], _, _), + do: {:pair, {pair, [kicker1, kicker2, kicker3] |> Enum.sort() |> Enum.reverse()}} + + defp score_hand(_, ranks, _), do: {:high_card, {ranks |> Enum.sort() |> Enum.reverse()}} defp sort_rank_asc({rank1, _}, {rank2, _}), do: rank1 <= rank2 - defp sort_count_then_rank_asc({rank1, count1}, {rank2, count2}), do: count1 <= count2 and rank1 <= rank2 + + defp sort_count_then_rank_asc({rank1, count1}, {rank2, count2}), + do: count1 <= count2 and rank1 <= rank2 # Compare different scores against each other first for {score, index} <- @scores |> Enum.with_index(1) do for other_score <- @scores |> Enum.drop(index) do - defp sort_scored_hands({_, unquote(score), _}, {_, unquote(other_score), _} ), do: true - defp sort_scored_hands({_, unquote(other_score), _}, {_, unquote(score), _} ), do: false + defp sort_scored_hands({_, unquote(score), _}, {_, unquote(other_score), _}), do: true + defp sort_scored_hands({_, unquote(other_score), _}, {_, unquote(score), _}), do: false end end # Additional rules for tiebreakers # Straight flush tie determined by high card - defp sort_scored_hands({_, :straight_flush, {high_a}}, {_, :straight_flush, {high_b}}), do: high_a >= high_b + defp sort_scored_hands({_, :straight_flush, {high_a}}, {_, :straight_flush, {high_b}}), + do: high_a >= high_b # 4-of-a-kind tie determined by rank, then by kicker - defp sort_scored_hands({_, :four_of_a_kind, {rank_a, _}}, {_, :four_of_a_kind, {rank_b, _}}) when rank_a > rank_b, do: true - defp sort_scored_hands({_, :four_of_a_kind, {rank_a, _}}, {_, :four_of_a_kind, {rank_b, _}}) when rank_a < rank_b, do: false - defp sort_scored_hands({_, :four_of_a_kind, {_, kicker_a}}, {_, :four_of_a_kind, {_, kicker_b}}), do: kicker_a >= kicker_b + defp sort_scored_hands({_, :four_of_a_kind, {rank_a, _}}, {_, :four_of_a_kind, {rank_b, _}}) + when rank_a > rank_b, + do: true + + defp sort_scored_hands({_, :four_of_a_kind, {rank_a, _}}, {_, :four_of_a_kind, {rank_b, _}}) + when rank_a < rank_b, + do: false + + defp sort_scored_hands({_, :four_of_a_kind, {_, kicker_a}}, {_, :four_of_a_kind, {_, kicker_b}}), + do: kicker_a >= kicker_b # Full house tie determined by triplet, then pair - defp sort_scored_hands({_, :full_house, {triplet_a, _}}, {_, :full_house, {triplet_b, _}}) when triplet_a > triplet_b, do: true - defp sort_scored_hands({_, :full_house, {triplet_a, _}}, {_, :full_house, {triplet_b, _}}) when triplet_a < triplet_b, do: false - defp sort_scored_hands({_, :full_house, {_, pair_a}}, {_, :full_house, {_, pair_b}}), do: pair_a >= pair_b + defp sort_scored_hands({_, :full_house, {triplet_a, _}}, {_, :full_house, {triplet_b, _}}) + when triplet_a > triplet_b, + do: true + + defp sort_scored_hands({_, :full_house, {triplet_a, _}}, {_, :full_house, {triplet_b, _}}) + when triplet_a < triplet_b, + do: false + + defp sort_scored_hands({_, :full_house, {_, pair_a}}, {_, :full_house, {_, pair_b}}), + do: pair_a >= pair_b # Flush tie determined by high card, comparing all 5 if necessary defp sort_scored_hands({_, :flush, {ranks_a}}, {_, :flush, {ranks_b}}), do: ranks_a >= ranks_b @@ -114,23 +146,54 @@ defmodule Poker do defp sort_scored_hands({_, :straight, {high_a}}, {_, :straight, {high_b}}), do: high_a >= high_b # 3-of-a-kind tie determined by triplet, then by high card, comparing both if necessary - defp sort_scored_hands({_, :three_of_a_kind, {triplet_a, _}}, {_, :three_of_a_kind, {triplet_b, _}}) when triplet_a > triplet_b, do: true - defp sort_scored_hands({_, :three_of_a_kind, {triplet_a, _}}, {_, :three_of_a_kind, {triplet_b, _}}) when triplet_a < triplet_b, do: false - defp sort_scored_hands({_, :three_of_a_kind, {_, ranks_a}}, {_, :three_of_a_kind, {_, ranks_b}}), do: ranks_a >= ranks_b + defp sort_scored_hands( + {_, :three_of_a_kind, {triplet_a, _}}, + {_, :three_of_a_kind, {triplet_b, _}} + ) + when triplet_a > triplet_b, + do: true + + defp sort_scored_hands( + {_, :three_of_a_kind, {triplet_a, _}}, + {_, :three_of_a_kind, {triplet_b, _}} + ) + when triplet_a < triplet_b, + do: false + + defp sort_scored_hands({_, :three_of_a_kind, {_, ranks_a}}, {_, :three_of_a_kind, {_, ranks_b}}), + do: ranks_a >= ranks_b # Two-pair tie determined by high pair, then low pair, then by kicker - defp sort_scored_hands({_, :two_pair, {high_a, _, _}}, {_, :two_pair, {high_b, _, _}}) when high_a > high_b, do: true - defp sort_scored_hands({_, :two_pair, {high_a, _, _}}, {_, :two_pair, {high_b, _, _}}) when high_a < high_b, do: false - defp sort_scored_hands({_, :two_pair, {_, low_a, _}}, {_, :two_pair, {_, low_b, _}}) when low_a > low_b, do: true - defp sort_scored_hands({_, :two_pair, {_, low_a, _}}, {_, :two_pair, {_, low_b, _}}) when low_a < low_b, do: false - defp sort_scored_hands({_, :two_pair, {_, _, kicker_a}}, {_, :two_pair, {_, _, kicker_b}}), do: kicker_a >= kicker_b + defp sort_scored_hands({_, :two_pair, {high_a, _, _}}, {_, :two_pair, {high_b, _, _}}) + when high_a > high_b, + do: true + + defp sort_scored_hands({_, :two_pair, {high_a, _, _}}, {_, :two_pair, {high_b, _, _}}) + when high_a < high_b, + do: false + + defp sort_scored_hands({_, :two_pair, {_, low_a, _}}, {_, :two_pair, {_, low_b, _}}) + when low_a > low_b, + do: true + + defp sort_scored_hands({_, :two_pair, {_, low_a, _}}, {_, :two_pair, {_, low_b, _}}) + when low_a < low_b, + do: false + + defp sort_scored_hands({_, :two_pair, {_, _, kicker_a}}, {_, :two_pair, {_, _, kicker_b}}), + do: kicker_a >= kicker_b # Pair tie determined by pair rank, then by high card, comparing all 3 if necessary - defp sort_scored_hands({_, :pair, {pair_a, _}}, {_, :pair, {pair_b, _}}) when pair_a > pair_b, do: true - defp sort_scored_hands({_, :pair, {pair_a, _}}, {_, :pair, {pair_b, _}}) when pair_a < pair_b, do: false - defp sort_scored_hands({_, :pair, {_, kickers_a}}, {_, :pair, {_, kickers_b}}), do: kickers_a >= kickers_b + defp sort_scored_hands({_, :pair, {pair_a, _}}, {_, :pair, {pair_b, _}}) when pair_a > pair_b, + do: true + + defp sort_scored_hands({_, :pair, {pair_a, _}}, {_, :pair, {pair_b, _}}) when pair_a < pair_b, + do: false + + defp sort_scored_hands({_, :pair, {_, kickers_a}}, {_, :pair, {_, kickers_b}}), + do: kickers_a >= kickers_b # High-card tie determined by high card, comparing all 5 if necessary - defp sort_scored_hands({_, :high_card, {ranks_a}}, {_, :high_card, {ranks_b}}), do: ranks_a >= ranks_b + defp sort_scored_hands({_, :high_card, {ranks_a}}, {_, :high_card, {ranks_b}}), + do: ranks_a >= ranks_b end - diff --git a/exercises/poker/poker.exs b/exercises/poker/poker.exs index 676cc9d426..309ad858db 100644 --- a/exercises/poker/poker.exs +++ b/exercises/poker/poker.exs @@ -31,4 +31,3 @@ defmodule Poker do def best_hand(hands) do end end - diff --git a/exercises/poker/poker_test.exs b/exercises/poker/poker_test.exs index 9cc11eb567..45a22aca65 100644 --- a/exercises/poker/poker_test.exs +++ b/exercises/poker/poker_test.exs @@ -2,13 +2,13 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("poker.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule PokerTest do use ExUnit.Case - #@tag :pending + # @tag :pending test "single hand always wins" do high_of_jack = ~w(4S 5S 7H 8D JC) assert Poker.best_hand([high_of_jack]) == [high_of_jack] @@ -103,7 +103,10 @@ defmodule PokerTest do assert Poker.best_hand([three_aces_7_high, three_aces_8_high]) == [three_aces_8_high] three_aces_8_high_5_low = ~w(5S AH AS 8C AD) - assert Poker.best_hand([three_aces_8_high_5_low, three_aces_8_high]) == [three_aces_8_high_5_low] + + assert Poker.best_hand([three_aces_8_high_5_low, three_aces_8_high]) == [ + three_aces_8_high_5_low + ] end @tag :pending @@ -214,4 +217,3 @@ defmodule PokerTest do assert Poker.best_hand([straight_flush_to_8, straight_flush_to_9]) == [straight_flush_to_9] end end - diff --git a/exercises/prime-factors/example.exs b/exercises/prime-factors/example.exs index cb06589c27..11ba875cda 100644 --- a/exercises/prime-factors/example.exs +++ b/exercises/prime-factors/example.exs @@ -4,12 +4,8 @@ defmodule PrimeFactors do do_factors(number, 2, []) end - defp do_factors(1, _, acc), - do: Enum.reverse(acc) - defp do_factors(n, i, acc) when n < i * i, - do: Enum.reverse(acc, [n]) - defp do_factors(n, i, acc) when rem(n, i) == 0, - do: do_factors(div(n, i), i, [i | acc]) - defp do_factors(n, i, acc), - do: do_factors(n, i + 1, acc) + defp do_factors(1, _, acc), do: Enum.reverse(acc) + defp do_factors(n, i, acc) when n < i * i, do: Enum.reverse(acc, [n]) + defp do_factors(n, i, acc) when rem(n, i) == 0, do: do_factors(div(n, i), i, [i | acc]) + defp do_factors(n, i, acc), do: do_factors(n, i + 1, acc) end diff --git a/exercises/prime-factors/prime_factors.exs b/exercises/prime-factors/prime_factors.exs index 76378ca874..b5b07b0779 100644 --- a/exercises/prime-factors/prime_factors.exs +++ b/exercises/prime-factors/prime_factors.exs @@ -9,6 +9,5 @@ defmodule PrimeFactors do """ @spec factors_for(pos_integer) :: [pos_integer] def factors_for(number) do - end end diff --git a/exercises/prime-factors/prime_factors_test.exs b/exercises/prime-factors/prime_factors_test.exs index 2ba3845538..c9b745dc06 100644 --- a/exercises/prime-factors/prime_factors_test.exs +++ b/exercises/prime-factors/prime_factors_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("prime_factors.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule PrimeFactorsTest do use ExUnit.Case @@ -55,12 +55,12 @@ defmodule PrimeFactorsTest do @tag :pending test "901255" do - assert PrimeFactors.factors_for(901255) == [5, 17, 23, 461] + assert PrimeFactors.factors_for(901_255) == [5, 17, 23, 461] end @tag :pending test "93819012551" do - assert PrimeFactors.factors_for(93819012551) == [11, 9539, 894119] + assert PrimeFactors.factors_for(93_819_012_551) == [11, 9539, 894_119] end @tag :pending @@ -70,6 +70,6 @@ defmodule PrimeFactorsTest do # in under two sconds. Uncomment it if you want to test the efficiency of your # solution. test "10000000055" do - assert PrimeFactors.factors_for(10000000055) == [5, 2000000011] + assert PrimeFactors.factors_for(10_000_000_055) == [5, 2_000_000_011] end end diff --git a/exercises/protein-translation/example.exs b/exercises/protein-translation/example.exs index 580fa105f2..3c8319e9e8 100644 --- a/exercises/protein-translation/example.exs +++ b/exercises/protein-translation/example.exs @@ -2,7 +2,7 @@ defmodule ProteinTranslation do @doc """ Given an RNA string, return a list of proteins specified by codons, in order. """ - @spec of_rna(String.t()) :: { atom, list(String.t()) } + @spec of_rna(String.t()) :: {atom, list(String.t())} def of_rna(rna) do translate_rna(rna, []) end @@ -28,7 +28,7 @@ defmodule ProteinTranslation do UAG -> STOP UGA -> STOP """ - @spec of_codon(String.t()) :: { atom, String.t() } + @spec of_codon(String.t()) :: {atom, String.t()} def of_codon(codon) do translate_codon(codon) end @@ -40,23 +40,25 @@ defmodule ProteinTranslation do "Serine" => ~w(UCU UCC UCA UCG), "Tyrosine" => ~w(UAU UAC), "Cysteine" => ~w(UGU UGC), - "Tryptophan" => ~w(UGG), + "Tryptophan" => ~w(UGG) } @stop ~w(UAA UAG UGA) - defp translate_rna("", results), do: { :ok, Enum.reverse(results) } + defp translate_rna("", results), do: {:ok, Enum.reverse(results)} for codon <- @stop do - defp translate_rna(unquote(codon) <> _rest, results), do: { :ok, Enum.reverse(results) } - defp translate_codon(unquote(codon)), do: { :ok, "STOP" } + defp translate_rna(unquote(codon) <> _rest, results), do: {:ok, Enum.reverse(results)} + defp translate_codon(unquote(codon)), do: {:ok, "STOP"} end - for { protein, codons } <- @codons, codon <- codons do - defp translate_rna(unquote(codon) <> rest, results), do: translate_rna(rest, [unquote(protein) | results]) - defp translate_codon(unquote(codon)), do: { :ok, unquote(protein) } + for {protein, codons} <- @codons, + codon <- codons do + defp translate_rna(unquote(codon) <> rest, results), + do: translate_rna(rest, [unquote(protein) | results]) + + defp translate_codon(unquote(codon)), do: {:ok, unquote(protein)} end - defp translate_rna(_, _), do: { :error, "invalid RNA"} - defp translate_codon(_), do: { :error, "invalid codon"} + defp translate_rna(_, _), do: {:error, "invalid RNA"} + defp translate_codon(_), do: {:error, "invalid codon"} end - diff --git a/exercises/protein-translation/protein_translation.exs b/exercises/protein-translation/protein_translation.exs index ff8a3f011c..401b205099 100644 --- a/exercises/protein-translation/protein_translation.exs +++ b/exercises/protein-translation/protein_translation.exs @@ -2,7 +2,7 @@ defmodule ProteinTranslation do @doc """ Given an RNA string, return a list of proteins specified by codons, in order. """ - @spec of_rna(String.t()) :: { atom, list(String.t()) } + @spec of_rna(String.t()) :: {atom, list(String.t())} def of_rna(rna) do end @@ -27,8 +27,7 @@ defmodule ProteinTranslation do UAG -> STOP UGA -> STOP """ - @spec of_codon(String.t()) :: { atom, String.t() } + @spec of_codon(String.t()) :: {atom, String.t()} def of_codon(codon) do end end - diff --git a/exercises/protein-translation/protein_translation_test.exs b/exercises/protein-translation/protein_translation_test.exs index 9aba77b0a7..a9363a42c9 100644 --- a/exercises/protein-translation/protein_translation_test.exs +++ b/exercises/protein-translation/protein_translation_test.exs @@ -2,91 +2,91 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("protein_translation.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule ProteinTranslationTest do use ExUnit.Case - #@tag :pending + # @tag :pending test "AUG translates to methionine" do - assert ProteinTranslation.of_codon("AUG") == { :ok, "Methionine" } + assert ProteinTranslation.of_codon("AUG") == {:ok, "Methionine"} end @tag :pending test "identifies Phenylalanine codons" do - assert ProteinTranslation.of_codon("UUU") == { :ok, "Phenylalanine" } - assert ProteinTranslation.of_codon("UUC") == { :ok, "Phenylalanine" } + assert ProteinTranslation.of_codon("UUU") == {:ok, "Phenylalanine"} + assert ProteinTranslation.of_codon("UUC") == {:ok, "Phenylalanine"} end @tag :pending test "identifies Leucine codons" do - assert ProteinTranslation.of_codon("UUA") == { :ok, "Leucine" } - assert ProteinTranslation.of_codon("UUG") == { :ok, "Leucine" } + assert ProteinTranslation.of_codon("UUA") == {:ok, "Leucine"} + assert ProteinTranslation.of_codon("UUG") == {:ok, "Leucine"} end @tag :pending test "identifies Serine codons" do - assert ProteinTranslation.of_codon("UCU") == { :ok, "Serine" } - assert ProteinTranslation.of_codon("UCC") == { :ok, "Serine" } - assert ProteinTranslation.of_codon("UCA") == { :ok, "Serine" } - assert ProteinTranslation.of_codon("UCG") == { :ok, "Serine" } + assert ProteinTranslation.of_codon("UCU") == {:ok, "Serine"} + assert ProteinTranslation.of_codon("UCC") == {:ok, "Serine"} + assert ProteinTranslation.of_codon("UCA") == {:ok, "Serine"} + assert ProteinTranslation.of_codon("UCG") == {:ok, "Serine"} end @tag :pending test "identifies Tyrosine codons" do - assert ProteinTranslation.of_codon("UAU") == { :ok, "Tyrosine" } - assert ProteinTranslation.of_codon("UAC") == { :ok, "Tyrosine" } + assert ProteinTranslation.of_codon("UAU") == {:ok, "Tyrosine"} + assert ProteinTranslation.of_codon("UAC") == {:ok, "Tyrosine"} end @tag :pending test "identifies Cysteine codons" do - assert ProteinTranslation.of_codon("UGU") == { :ok, "Cysteine" } - assert ProteinTranslation.of_codon("UGC") == { :ok, "Cysteine" } + assert ProteinTranslation.of_codon("UGU") == {:ok, "Cysteine"} + assert ProteinTranslation.of_codon("UGC") == {:ok, "Cysteine"} end @tag :pending test "identifies Tryptophan codons" do - assert ProteinTranslation.of_codon("UGG") == { :ok, "Tryptophan" } + assert ProteinTranslation.of_codon("UGG") == {:ok, "Tryptophan"} end @tag :pending test "identifies stop codons" do - assert ProteinTranslation.of_codon("UAA") == { :ok, "STOP" } - assert ProteinTranslation.of_codon("UAG") == { :ok, "STOP" } - assert ProteinTranslation.of_codon("UGA") == { :ok, "STOP" } + assert ProteinTranslation.of_codon("UAA") == {:ok, "STOP"} + assert ProteinTranslation.of_codon("UAG") == {:ok, "STOP"} + assert ProteinTranslation.of_codon("UGA") == {:ok, "STOP"} end @tag :pending test "translates rna strand into correct protein" do strand = "AUGUUUUGG" - assert ProteinTranslation.of_rna(strand) == { :ok, ~w(Methionine Phenylalanine Tryptophan) } + assert ProteinTranslation.of_rna(strand) == {:ok, ~w(Methionine Phenylalanine Tryptophan)} end @tag :pending test "stops translation if stop codon present" do strand = "AUGUUUUAA" - assert ProteinTranslation.of_rna(strand) == { :ok, ~w(Methionine Phenylalanine) } + assert ProteinTranslation.of_rna(strand) == {:ok, ~w(Methionine Phenylalanine)} end @tag :pending test "stops translation of longer strand" do strand = "UGGUGUUAUUAAUGGUUU" - assert ProteinTranslation.of_rna(strand) == { :ok, ~w(Tryptophan Cysteine Tyrosine) } + assert ProteinTranslation.of_rna(strand) == {:ok, ~w(Tryptophan Cysteine Tyrosine)} end @tag :pending test "invalid RNA" do - assert ProteinTranslation.of_rna("CARROT") == { :error, "invalid RNA" } + assert ProteinTranslation.of_rna("CARROT") == {:error, "invalid RNA"} end @tag :pending test "invalid codon at end of RNA" do - assert ProteinTranslation.of_rna("UUUROT") == { :error, "invalid RNA" } + assert ProteinTranslation.of_rna("UUUROT") == {:error, "invalid RNA"} end @tag :pending test "invalid codon" do - assert ProteinTranslation.of_codon("INVALID") == { :error, "invalid codon" } + assert ProteinTranslation.of_codon("INVALID") == {:error, "invalid codon"} end end diff --git a/exercises/pythagorean-triplet/example.exs b/exercises/pythagorean-triplet/example.exs index d7e84a9ec7..cfeaabf79a 100644 --- a/exercises/pythagorean-triplet/example.exs +++ b/exercises/pythagorean-triplet/example.exs @@ -1,5 +1,4 @@ defmodule Triplet do - @doc """ Calculates sum of a given triplet of integers. """ @@ -21,7 +20,7 @@ defmodule Triplet do """ @spec pythagorean?([non_neg_integer]) :: boolean def pythagorean?([a, b, c]) do - (a * a) + (b * b) == (c * c) + a * a + b * b == c * c end defp select?(triplet) do @@ -40,7 +39,8 @@ defmodule Triplet do for x <- Enum.to_list(min..max), y <- Enum.to_list(x..max), z <- Enum.to_list(y..max), - select?([x, y, z]), do: [x, y, z] + select?([x, y, z]), + do: [x, y, z] end @doc """ @@ -51,6 +51,7 @@ defmodule Triplet do for x <- Enum.to_list(min..max), y <- Enum.to_list(x..max), z <- Enum.to_list(y..max), - select?([x, y, z], sum), do: [x, y, z] + select?([x, y, z], sum), + do: [x, y, z] end end diff --git a/exercises/pythagorean-triplet/pythagorean_triplet.exs b/exercises/pythagorean-triplet/pythagorean_triplet.exs index b3720b9087..5b634ab3d1 100644 --- a/exercises/pythagorean-triplet/pythagorean_triplet.exs +++ b/exercises/pythagorean-triplet/pythagorean_triplet.exs @@ -1,11 +1,9 @@ defmodule Triplet do - @doc """ Calculates sum of a given triplet of integers. """ @spec sum([non_neg_integer]) :: non_neg_integer def sum(triplet) do - end @doc """ @@ -13,7 +11,6 @@ defmodule Triplet do """ @spec product([non_neg_integer]) :: non_neg_integer def product(triplet) do - end @doc """ @@ -21,7 +18,6 @@ defmodule Triplet do """ @spec pythagorean?([non_neg_integer]) :: boolean def pythagorean?([a, b, c]) do - end @doc """ @@ -29,7 +25,6 @@ defmodule Triplet do """ @spec generate(non_neg_integer, non_neg_integer) :: [list(non_neg_integer)] def generate(min, max) do - end @doc """ diff --git a/exercises/pythagorean-triplet/pythagorean_triplet_test.exs b/exercises/pythagorean-triplet/pythagorean_triplet_test.exs index 84bdbe91cc..5c9e13c80b 100644 --- a/exercises/pythagorean-triplet/pythagorean_triplet_test.exs +++ b/exercises/pythagorean-triplet/pythagorean_triplet_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("pythagorean_triplet.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule PythagoreanTripletTest do use ExUnit.Case @@ -47,6 +47,6 @@ defmodule PythagoreanTripletTest do @tag :pending test "triplets where sum is 180 and max factor is 100" do triplets = Triplet.generate(1, 100, 180) - assert Enum.map(triplets, &Triplet.product/1) == [118080, 168480, 202500] + assert Enum.map(triplets, &Triplet.product/1) == [118_080, 168_480, 202_500] end end diff --git a/exercises/queen-attack/example.exs b/exercises/queen-attack/example.exs index fb59a40964..e57ebc6771 100644 --- a/exercises/queen-attack/example.exs +++ b/exercises/queen-attack/example.exs @@ -1,5 +1,5 @@ defmodule Queens do - @type t :: %Queens{ white: {integer, integer}, black: {integer, integer} } + @type t :: %Queens{white: {integer, integer}, black: {integer, integer}} defstruct white: {0, 3}, black: {7, 3} @doc """ @@ -7,10 +7,12 @@ defmodule Queens do """ @spec new() :: Queens.t() @spec new({integer, integer}, {integer, integer}) :: Queens.t() - def new(same, same), do: raise ArgumentError + def new(same, same), do: raise(ArgumentError) + def new(white, black) do %Queens{white: white, black: black} end + def new, do: %Queens{} @doc """ @@ -18,7 +20,7 @@ defmodule Queens do white and black queen locations shown """ @spec to_string(Queens.t()) :: String.t() - def to_string(%Queens{ white: white, black: black }) do + def to_string(%Queens{white: white, black: black}) do generate_board() |> insert_queen(white, "W") |> insert_queen(black, "B") @@ -30,7 +32,7 @@ defmodule Queens do Checks if the queens can attack each other """ @spec can_attack?(Queens.t()) :: boolean - def can_attack?(%Queens{ white: white, black: black }) do + def can_attack?(%Queens{white: white, black: black}) do {white_x, white_y} = white {black_x, black_y} = black white_x == black_x || white_y == black_y || diagonal?(white, black) @@ -41,9 +43,9 @@ defmodule Queens do end defp insert_queen(board, {x, y}, letter) do - List.update_at board, x, fn(row) -> - List.replace_at row, y, letter - end + List.update_at(board, x, fn row -> + List.replace_at(row, y, letter) + end) end defp generate_board do diff --git a/exercises/queen-attack/queen_attack.exs b/exercises/queen-attack/queen_attack.exs index b94e9a54c4..064b9edc3c 100644 --- a/exercises/queen-attack/queen_attack.exs +++ b/exercises/queen-attack/queen_attack.exs @@ -1,5 +1,5 @@ defmodule Queens do - @type t :: %Queens{ black: {integer, integer}, white: {integer, integer} } + @type t :: %Queens{black: {integer, integer}, white: {integer, integer}} defstruct black: nil, white: nil @doc """ @@ -8,7 +8,6 @@ defmodule Queens do @spec new() :: Queens.t() @spec new({integer, integer}, {integer, integer}) :: Queens.t() def new(white, black) do - end @doc """ @@ -17,7 +16,6 @@ defmodule Queens do """ @spec to_string(Queens.t()) :: String.t() def to_string(queens) do - end @doc """ @@ -25,6 +23,5 @@ defmodule Queens do """ @spec can_attack?(Queens.t()) :: boolean def can_attack?(queens) do - end end diff --git a/exercises/rail-fence-cipher/example.exs b/exercises/rail-fence-cipher/example.exs index 2a08c626c7..60d080ddbc 100644 --- a/exercises/rail-fence-cipher/example.exs +++ b/exercises/rail-fence-cipher/example.exs @@ -2,43 +2,46 @@ defmodule RailFenceCipher do @doc """ Encode a given plaintext to the corresponding rail fence ciphertext """ - @spec encode(String.t, pos_integer) :: String.t + @spec encode(String.t(), pos_integer) :: String.t() def encode(str, 1), do: str + def encode(str, rails) do str - |> String.codepoints + |> String.codepoints() |> fill_fence(rails) - |> Enum.join + |> Enum.join() end @doc """ Decode a given rail fence ciphertext to the corresponding plaintext """ - @spec decode(String.t, pos_integer) :: String.t + @spec decode(String.t(), pos_integer) :: String.t() def decode(str, 1), do: str + def decode(str, rails) do - 0..String.length(str) - 1 - |> Enum.to_list + 0..(String.length(str) - 1) + |> Enum.to_list() |> fill_fence(rails) |> extract_original(str) end defp extract_original(fence, str) do - 0..String.length(str) - 1 + 0..(String.length(str) - 1) |> Enum.map(fn i -> String.at(str, Enum.find_index(fence, &(&1 == i))) end) - |> Enum.join + |> Enum.join() end defp fill_fence(list_chars, rails) do - rail_zigzag_indexes = Enum.concat(Enum.to_list(0..rails - 1), Enum.to_list(rails - 2..1)) + rail_zigzag_indexes = Enum.concat(Enum.to_list(0..(rails - 1)), Enum.to_list((rails - 2)..1)) + create_empty_fence(rails, length(list_chars)) |> set_chars_to_fence(list_chars, rail_zigzag_indexes) end defp create_empty_fence(rows, cols) do - 0..rows - 1 + 0..(rows - 1) |> Enum.map(fn _ -> List.duplicate(nil, cols) end) @@ -46,12 +49,12 @@ defmodule RailFenceCipher do defp set_chars_to_fence(fence, chars, pos_in_zigzag) do chars - |> Enum.with_index + |> Enum.with_index() |> Enum.reduce(fence, fn {char, index}, acc -> - rail_ind = Enum.at(pos_in_zigzag, rem(index, length(pos_in_zigzag))) - List.update_at(acc, rail_ind, &(List.update_at(&1, index, fn _ -> char end))) - end) - |> List.flatten + rail_ind = Enum.at(pos_in_zigzag, rem(index, length(pos_in_zigzag))) + List.update_at(acc, rail_ind, &List.update_at(&1, index, fn _ -> char end)) + end) + |> List.flatten() |> Enum.filter(&(&1 != nil)) end end diff --git a/exercises/rail-fence-cipher/rail_fence_cipher.exs b/exercises/rail-fence-cipher/rail_fence_cipher.exs index 779899aa76..f59b6fcf22 100644 --- a/exercises/rail-fence-cipher/rail_fence_cipher.exs +++ b/exercises/rail-fence-cipher/rail_fence_cipher.exs @@ -2,16 +2,14 @@ defmodule RailFenceCipher do @doc """ Encode a given plaintext to the corresponding rail fence ciphertext """ - @spec encode(String.t, pos_integer) :: String.t + @spec encode(String.t(), pos_integer) :: String.t() def encode(str, rails) do - end @doc """ Decode a given rail fence ciphertext to the corresponding plaintext """ - @spec decode(String.t, pos_integer) :: String.t + @spec decode(String.t(), pos_integer) :: String.t() def decode(str, rails) do - end end diff --git a/exercises/rail-fence-cipher/rail_fence_cipher_test.exs b/exercises/rail-fence-cipher/rail_fence_cipher_test.exs index 21dde5aef6..2d890cf048 100644 --- a/exercises/rail-fence-cipher/rail_fence_cipher_test.exs +++ b/exercises/rail-fence-cipher/rail_fence_cipher_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("rail_fence_cipher.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule RailFenceCipherTest do use ExUnit.Case diff --git a/exercises/raindrops/example.exs b/exercises/raindrops/example.exs index 2ad052304d..ac9583baf9 100644 --- a/exercises/raindrops/example.exs +++ b/exercises/raindrops/example.exs @@ -1,5 +1,6 @@ defmodule Raindrops do - def convert(number), do: output { [sound(number,3), sound(number,5), sound(number,7)], number } + def convert(number), + do: output({[sound(number, 3), sound(number, 5), sound(number, 7)], number}) defp sound(n, 3) when rem(n, 3) == 0, do: "Pling" defp sound(n, 5) when rem(n, 5) == 0, do: "Plang" @@ -7,5 +8,5 @@ defmodule Raindrops do defp sound(_, _), do: "" defp output({["", "", ""], number}), do: "#{number}" - defp output({sounds, _}), do: Enum.join sounds + defp output({sounds, _}), do: Enum.join(sounds) end diff --git a/exercises/raindrops/raindrops.exs b/exercises/raindrops/raindrops.exs index 8a42b9d1bf..41ef30074c 100644 --- a/exercises/raindrops/raindrops.exs +++ b/exercises/raindrops/raindrops.exs @@ -8,8 +8,7 @@ defmodule Raindrops do - If the number does not contain 3, 5, or 7 as a prime factor, just pass the number's digits straight through. """ - @spec convert(pos_integer) :: String.t + @spec convert(pos_integer) :: String.t() def convert(number) do - end end diff --git a/exercises/raindrops/raindrops_test.exs b/exercises/raindrops/raindrops_test.exs index 91e0d63f04..ff231fb7a6 100644 --- a/exercises/raindrops/raindrops_test.exs +++ b/exercises/raindrops/raindrops_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("raindrops.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule RaindropsTest do use ExUnit.Case diff --git a/exercises/rna-transcription/example.exs b/exercises/rna-transcription/example.exs index 362ba86858..41ff5f899e 100644 --- a/exercises/rna-transcription/example.exs +++ b/exercises/rna-transcription/example.exs @@ -8,7 +8,7 @@ defmodule RNATranscription do 'UGAC' """ def to_rna(dna) do - Enum.map dna, &transcribe(&1) + Enum.map(dna, &transcribe(&1)) end defp transcribe(?C), do: ?G diff --git a/exercises/rna-transcription/rna_transcription.exs b/exercises/rna-transcription/rna_transcription.exs index 0ac5bfa73d..03ea58d02d 100644 --- a/exercises/rna-transcription/rna_transcription.exs +++ b/exercises/rna-transcription/rna_transcription.exs @@ -9,6 +9,5 @@ defmodule RNATranscription do """ @spec to_rna([char]) :: [char] def to_rna(dna) do - end end diff --git a/exercises/rna-transcription/rna_transcription_test.exs b/exercises/rna-transcription/rna_transcription_test.exs index 6522442e37..678d2227b4 100644 --- a/exercises/rna-transcription/rna_transcription_test.exs +++ b/exercises/rna-transcription/rna_transcription_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("rna_transcription.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule RNATranscriptionTest do use ExUnit.Case diff --git a/exercises/robot-simulator/example.exs b/exercises/robot-simulator/example.exs index e9d31705d3..b1ff985016 100644 --- a/exercises/robot-simulator/example.exs +++ b/exercises/robot-simulator/example.exs @@ -18,35 +18,49 @@ defmodule RobotSimulator do Valid instructions are: "R" (turn right), "L", (turn left), and "A" (advance) """ - @spec simulate(robot :: %RobotSimulator{}, instructions :: String.t ) :: any + @spec simulate(robot :: %RobotSimulator{}, instructions :: String.t()) :: any def simulate(%RobotSimulator{} = robot, instructions) do - instructions |> String.graphemes |> Enum.reduce(robot, &move/2) + instructions |> String.graphemes() |> Enum.reduce(robot, &move/2) end def position(%RobotSimulator{position: pos}), do: pos def direction(%RobotSimulator{direction: dir}), do: dir defp orient(%RobotSimulator{} = robot, direction) when direction in @valid_directions do - %{ robot | direction: direction } + %{robot | direction: direction} end - defp orient({ :error, _ } = error, _), do: error - defp orient(_, _), do: { :error, "invalid direction" } - defp place(%RobotSimulator{} = robot, { x, y } = position) when is_integer(x) and is_integer(y) do - %{ robot | position: position } + defp orient({:error, _} = error, _), do: error + defp orient(_, _), do: {:error, "invalid direction"} + + defp place(%RobotSimulator{} = robot, {x, y} = position) when is_integer(x) and is_integer(y) do + %{robot | position: position} end - defp place(_, _), do: { :error, "invalid position" } - - defp move("R", %RobotSimulator{ direction: direction } = robot), do: robot |> orient(direction |> rotate_right) - defp move("L", %RobotSimulator{ direction: direction } = robot), do: robot |> orient(direction |> rotate_left) - defp move("A", %RobotSimulator{ direction: :north, position: { x, y } } = robot), do: robot |> place({ x, y + 1 }) - defp move("A", %RobotSimulator{ direction: :east, position: { x, y } } = robot), do: robot |> place({ x + 1, y }) - defp move("A", %RobotSimulator{ direction: :south, position: { x, y } } = robot), do: robot |> place({ x, y - 1 }) - defp move("A", %RobotSimulator{ direction: :west, position: { x, y } } = robot), do: robot |> place({ x - 1, y }) - defp move(_, { :error, _ } = error), do: error - defp move(_, _), do: { :error, "invalid instruction" } - - for [curr, right] <- @valid_directions |> Stream.cycle |> Enum.take(5) |> Enum.chunk(2, 1) do + + defp place(_, _), do: {:error, "invalid position"} + + defp move("R", %RobotSimulator{direction: direction} = robot), + do: robot |> orient(direction |> rotate_right) + + defp move("L", %RobotSimulator{direction: direction} = robot), + do: robot |> orient(direction |> rotate_left) + + defp move("A", %RobotSimulator{direction: :north, position: {x, y}} = robot), + do: robot |> place({x, y + 1}) + + defp move("A", %RobotSimulator{direction: :east, position: {x, y}} = robot), + do: robot |> place({x + 1, y}) + + defp move("A", %RobotSimulator{direction: :south, position: {x, y}} = robot), + do: robot |> place({x, y - 1}) + + defp move("A", %RobotSimulator{direction: :west, position: {x, y}} = robot), + do: robot |> place({x - 1, y}) + + defp move(_, {:error, _} = error), do: error + defp move(_, _), do: {:error, "invalid instruction"} + + for [curr, right] <- @valid_directions |> Stream.cycle() |> Enum.take(5) |> Enum.chunk(2, 1) do defp rotate_right(unquote(curr)), do: unquote(right) defp rotate_left(unquote(right)), do: unquote(curr) end diff --git a/exercises/robot-simulator/robot_simulator.exs b/exercises/robot-simulator/robot_simulator.exs index 8a942e01ea..55875154e7 100644 --- a/exercises/robot-simulator/robot_simulator.exs +++ b/exercises/robot-simulator/robot_simulator.exs @@ -4,7 +4,7 @@ defmodule RobotSimulator do Valid directions are: `:north`, `:east`, `:south`, `:west` """ - @spec create(direction :: atom, position :: { integer, integer }) :: any + @spec create(direction :: atom, position :: {integer, integer}) :: any def create(direction \\ nil, position \\ nil) do end @@ -13,7 +13,7 @@ defmodule RobotSimulator do Valid instructions are: "R" (turn right), "L", (turn left), and "A" (advance) """ - @spec simulate(robot :: any, instructions :: String.t ) :: any + @spec simulate(robot :: any, instructions :: String.t()) :: any def simulate(robot, instructions) do end @@ -24,14 +24,12 @@ defmodule RobotSimulator do """ @spec direction(robot :: any) :: atom def direction(robot) do - end @doc """ Return the robot's position. """ - @spec position(robot :: any) :: { integer, integer } + @spec position(robot :: any) :: {integer, integer} def position(robot) do - end end diff --git a/exercises/robot-simulator/robot_simulator_test.exs b/exercises/robot-simulator/robot_simulator_test.exs index cb342238f1..f4ead145ee 100644 --- a/exercises/robot-simulator/robot_simulator_test.exs +++ b/exercises/robot-simulator/robot_simulator_test.exs @@ -2,41 +2,41 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("robot_simulator.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule RobotSimulatorTest do use ExUnit.Case test "create has sensible defaults" do - robot = RobotSimulator.create - assert RobotSimulator.position(robot) == { 0, 0 } + robot = RobotSimulator.create() + assert RobotSimulator.position(robot) == {0, 0} assert RobotSimulator.direction(robot) == :north end @tag :pending test "create works with valid arguments" do - robot = RobotSimulator.create(:north, { 0, 0 }) - assert RobotSimulator.position(robot) == { 0, 0 } + robot = RobotSimulator.create(:north, {0, 0}) + assert RobotSimulator.position(robot) == {0, 0} assert RobotSimulator.direction(robot) == :north - robot = RobotSimulator.create(:south, { -10, 0 }) - assert RobotSimulator.position(robot) == { -10, 0 } + robot = RobotSimulator.create(:south, {-10, 0}) + assert RobotSimulator.position(robot) == {-10, 0} assert RobotSimulator.direction(robot) == :south - robot = RobotSimulator.create(:east, { 0, 10 }) - assert RobotSimulator.position(robot) == { 0, 10 } + robot = RobotSimulator.create(:east, {0, 10}) + assert RobotSimulator.position(robot) == {0, 10} assert RobotSimulator.direction(robot) == :east - robot = RobotSimulator.create(:west, { 100, -100 }) - assert RobotSimulator.position(robot) == { 100, -100 } + robot = RobotSimulator.create(:west, {100, -100}) + assert RobotSimulator.position(robot) == {100, -100} assert RobotSimulator.direction(robot) == :west end @tag :pending test "create errors if invalid direction given" do position = {0, 0} - invalid_direction = { :error, "invalid direction" } + invalid_direction = {:error, "invalid direction"} assert RobotSimulator.create(:invalid, position) == invalid_direction assert RobotSimulator.create(0, position) == invalid_direction @@ -46,35 +46,36 @@ defmodule RobotSimulatorTest do @tag :pending test "create errors if invalid position given" do direction = :north - invalid_position = { :error, "invalid position" } + invalid_position = {:error, "invalid position"} - assert RobotSimulator.create(direction, { 0, 0, 0 }) == invalid_position - assert RobotSimulator.create(direction, { 0, :invalid }) == invalid_position - assert RobotSimulator.create(direction, { "0", 0 }) == invalid_position + assert RobotSimulator.create(direction, {0, 0, 0}) == invalid_position + assert RobotSimulator.create(direction, {0, :invalid}) == invalid_position + assert RobotSimulator.create(direction, {"0", 0}) == invalid_position assert RobotSimulator.create(direction, "invalid") == invalid_position - assert RobotSimulator.create(direction, 0 ) == invalid_position + assert RobotSimulator.create(direction, 0) == invalid_position assert RobotSimulator.create(direction, [0, 0]) == invalid_position assert RobotSimulator.create(direction, nil) == invalid_position end @tag :pending test "simulate robots" do - robot1 = RobotSimulator.create(:north, { 0, 0 }) |> RobotSimulator.simulate("LAAARALA") + robot1 = RobotSimulator.create(:north, {0, 0}) |> RobotSimulator.simulate("LAAARALA") assert RobotSimulator.direction(robot1) == :west - assert RobotSimulator.position(robot1) == { -4, 1 } + assert RobotSimulator.position(robot1) == {-4, 1} - robot2 = RobotSimulator.create(:east, { 2, -7 }) |> RobotSimulator.simulate("RRAAAAALA") + robot2 = RobotSimulator.create(:east, {2, -7}) |> RobotSimulator.simulate("RRAAAAALA") assert RobotSimulator.direction(robot2) == :south - assert RobotSimulator.position(robot2) == { -3, -8 } + assert RobotSimulator.position(robot2) == {-3, -8} - robot3 = RobotSimulator.create(:south, { 8, 4 }) |> RobotSimulator.simulate("LAAARRRALLLL") + robot3 = RobotSimulator.create(:south, {8, 4}) |> RobotSimulator.simulate("LAAARRRALLLL") assert RobotSimulator.direction(robot3) == :north - assert RobotSimulator.position(robot3) == { 11, 5 } + assert RobotSimulator.position(robot3) == {11, 5} end @tag :pending test "simulate errors on invalid instructions" do - assert RobotSimulator.create |> RobotSimulator.simulate("UUDDLRLRBASTART") == { :error, "invalid instruction" } + assert RobotSimulator.create() |> RobotSimulator.simulate("UUDDLRLRBASTART") == + {:error, "invalid instruction"} end end diff --git a/exercises/roman-numerals/example.exs b/exercises/roman-numerals/example.exs index d1a05dfac7..14624a69e3 100644 --- a/exercises/roman-numerals/example.exs +++ b/exercises/roman-numerals/example.exs @@ -1,27 +1,28 @@ defmodule Roman do @numerals [ [1000, "M"], - [ 900, "CM"], - [ 500, "D"], - [ 400, "CD"], - [ 100, "C"], - [ 90, "XC"], - [ 50, "L"], - [ 40, "XL"], - [ 10, "X"], - [ 9, "IX"], - [ 5, "V"], - [ 4, "IV"], - [ 1, "I"] + [900, "CM"], + [500, "D"], + [400, "CD"], + [100, "C"], + [90, "XC"], + [50, "L"], + [40, "XL"], + [10, "X"], + [9, "IX"], + [5, "V"], + [4, "IV"], + [1, "I"] ] def numerals(0), do: "" + def numerals(number) do [part, letter] = largest_factor(number) letter <> numerals(number - part) end defp largest_factor(number) do - hd Enum.filter(@numerals, fn([p, _]) -> p <= number end) + hd(Enum.filter(@numerals, fn [p, _] -> p <= number end)) end end diff --git a/exercises/roman-numerals/roman.exs b/exercises/roman-numerals/roman.exs index e391e9f40a..135c1cb737 100644 --- a/exercises/roman-numerals/roman.exs +++ b/exercises/roman-numerals/roman.exs @@ -2,7 +2,7 @@ defmodule Roman do @doc """ Convert the number to a roman number. """ - @spec numerals(pos_integer) :: String.t + @spec numerals(pos_integer) :: String.t() def numerals(number) do end end diff --git a/exercises/roman-numerals/roman_numerals_test.exs b/exercises/roman-numerals/roman_numerals_test.exs index ba3f43417c..d1540a977e 100644 --- a/exercises/roman-numerals/roman_numerals_test.exs +++ b/exercises/roman-numerals/roman_numerals_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("roman.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule RomanTest do use ExUnit.Case diff --git a/exercises/rotational-cipher/example.exs b/exercises/rotational-cipher/example.exs index ed0fbd29f5..df88c76315 100644 --- a/exercises/rotational-cipher/example.exs +++ b/exercises/rotational-cipher/example.exs @@ -4,14 +4,19 @@ defmodule RotationalCipher do for shift <- 0..25 do plain = String.split(@alphabet, "", trim: true) - cipher = @alphabet - |> Kernel.<>(@alphabet) - |> String.split("", trim: true) - |> Enum.drop(shift) - |> Enum.take(@alphabet_size) + + cipher = + @alphabet + |> Kernel.<>(@alphabet) + |> String.split("", trim: true) + |> Enum.drop(shift) + |> Enum.take(@alphabet_size) + for {p, c} <- Enum.zip(plain, cipher) do def translate(unquote(p), unquote(shift)), do: unquote(c) - def translate(unquote(p |> String.upcase), unquote(shift)), do: unquote(c |> String.upcase) + + def translate(unquote(p |> String.upcase()), unquote(shift)), + do: unquote(c |> String.upcase()) end end @@ -29,7 +34,6 @@ defmodule RotationalCipher do def rotate(text, shift) do text |> String.split("", trim: true) - |> Enum.map_join(&(translate(&1, shift))) + |> Enum.map_join(&translate(&1, shift)) end end - diff --git a/exercises/rotational-cipher/rotational_cipher.exs b/exercises/rotational-cipher/rotational_cipher.exs index 69b30c35c3..ecc2bf21b7 100644 --- a/exercises/rotational-cipher/rotational_cipher.exs +++ b/exercises/rotational-cipher/rotational_cipher.exs @@ -10,4 +10,3 @@ defmodule RotationalCipher do def rotate(text, shift) do end end - diff --git a/exercises/rotational-cipher/rotational_cipher_test.exs b/exercises/rotational-cipher/rotational_cipher_test.exs index 0a5ee630e3..80f81ab9db 100644 --- a/exercises/rotational-cipher/rotational_cipher_test.exs +++ b/exercises/rotational-cipher/rotational_cipher_test.exs @@ -2,13 +2,13 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("rotational_cipher.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule RotationalCipherTest do use ExUnit.Case - #@tag :pending + # @tag :pending test "rotate a by 1" do plaintext = "a" shift = 1 @@ -75,6 +75,8 @@ defmodule RotationalCipherTest do test "rotate all letters" do plaintext = "The quick brown fox jumps over the lazy dog." shift = 13 - assert RotationalCipher.rotate(plaintext, shift) == "Gur dhvpx oebja sbk whzcf bire gur ynml qbt." + + assert RotationalCipher.rotate(plaintext, shift) == + "Gur dhvpx oebja sbk whzcf bire gur ynml qbt." end end diff --git a/exercises/run-length-encoding/example.exs b/exercises/run-length-encoding/example.exs index 7bdf777fc3..6c641ae93d 100644 --- a/exercises/run-length-encoding/example.exs +++ b/exercises/run-length-encoding/example.exs @@ -1,20 +1,32 @@ defmodule RunLengthEncoder do - - @spec encode(String.t) :: String.t + @spec encode(String.t()) :: String.t() def encode(string) do Regex.scan(~r/([a-zA-Z\s])\1*/, string) - |> Enum.map_join(fn([run, c]) -> + |> Enum.map_join(fn [run, c] -> times = String.length(run) - number = if times == 1 do "" else times end - "#{number}#{c}" + + number = + if times == 1 do + "" + else + times + end + + "#{number}#{c}" end) end - @spec decode(String.t) :: String.t + @spec decode(String.t()) :: String.t() def decode(string) do Regex.scan(~r/(\d*)(.)/, string) - |> Enum.map_join(fn [_,n,c] -> - times = if n == "" do 1 else String.to_integer(n) end + |> Enum.map_join(fn [_, n, c] -> + times = + if n == "" do + 1 + else + String.to_integer(n) + end + String.duplicate(c, times) end) end diff --git a/exercises/run-length-encoding/rle.exs b/exercises/run-length-encoding/rle.exs index 36f3e9a5bf..25e21d78a7 100644 --- a/exercises/run-length-encoding/rle.exs +++ b/exercises/run-length-encoding/rle.exs @@ -6,13 +6,11 @@ defmodule RunLengthEncoder do It should also be able to reconstruct the data into its original form. "2A3B4C" => "AABBBCCCC" """ - @spec encode(String.t) :: String.t + @spec encode(String.t()) :: String.t() def encode(string) do - end - @spec decode(String.t) :: String.t + @spec decode(String.t()) :: String.t() def decode(string) do - end end diff --git a/exercises/run-length-encoding/rle_test.exs b/exercises/run-length-encoding/rle_test.exs index 0989feec90..1099f4edb3 100644 --- a/exercises/run-length-encoding/rle_test.exs +++ b/exercises/run-length-encoding/rle_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("rle.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule RunLengthEncoderTest do use ExUnit.Case @@ -24,7 +24,8 @@ defmodule RunLengthEncoderTest do @tag :pending test "encode single characters mixed with repeated characters" do - assert RunLengthEncoder.encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB") === "12WB12W3B24WB" + assert RunLengthEncoder.encode("WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB") === + "12WB12W3B24WB" end @tag :pending @@ -54,7 +55,8 @@ defmodule RunLengthEncoderTest do @tag :pending test "decode single characters with repeated characters" do - assert RunLengthEncoder.decode("12WB12W3B24WB") === "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB" + assert RunLengthEncoder.decode("12WB12W3B24WB") === + "WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWWWWWWWWWWWWWWWWWWWWWWWB" end @tag :pending diff --git a/exercises/saddle-points/example.exs b/exercises/saddle-points/example.exs index cc4529b67d..e0cacc867f 100644 --- a/exercises/saddle-points/example.exs +++ b/exercises/saddle-points/example.exs @@ -24,7 +24,7 @@ defmodule SaddlePoints do def columns(str) do str |> rows - |> List.zip + |> List.zip() |> Enum.map(&Tuple.to_list/1) end @@ -36,6 +36,7 @@ defmodule SaddlePoints do def saddle_points(str) do rows = rows(str) columns = columns(str) + rows |> generate_coordinates |> Enum.filter(&is_saddle_point?(&1, rows, columns)) @@ -57,13 +58,13 @@ defmodule SaddlePoints do defp generate_coordinates(rows) do rows - |> Enum.with_index + |> Enum.with_index() |> Enum.flat_map(&generate_coordinates_row/1) end defp generate_coordinates_row({row, row_index}) do row - |> Enum.with_index + |> Enum.with_index() |> Enum.map(fn {_, col_index} -> {row_index, col_index} end) end end diff --git a/exercises/saddle-points/saddle_points.exs b/exercises/saddle-points/saddle_points.exs index ace6210f32..644cb9c5f0 100644 --- a/exercises/saddle-points/saddle_points.exs +++ b/exercises/saddle-points/saddle_points.exs @@ -5,7 +5,6 @@ defmodule SaddlePoints do """ @spec rows(String.t()) :: [[integer]] def rows(str) do - end @doc """ @@ -14,7 +13,6 @@ defmodule SaddlePoints do """ @spec columns(String.t()) :: [[integer]] def columns(str) do - end @doc """ @@ -23,6 +21,5 @@ defmodule SaddlePoints do """ @spec saddle_points(String.t()) :: [{integer, integer}] def saddle_points(str) do - end end diff --git a/exercises/saddle-points/saddle_points_test.exs b/exercises/saddle-points/saddle_points_test.exs index b28bb51570..c817eab80b 100644 --- a/exercises/saddle-points/saddle_points_test.exs +++ b/exercises/saddle-points/saddle_points_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("saddle_points.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule SaddlePointsTest do use ExUnit.Case diff --git a/exercises/say/say.exs b/exercises/say/say.exs index c0bfc00187..82842fbe5b 100644 --- a/exercises/say/say.exs +++ b/exercises/say/say.exs @@ -2,7 +2,7 @@ defmodule Say do @doc """ Translate a positive integer into English. """ - @spec in_english(integer) :: {atom, String.t} + @spec in_english(integer) :: {atom, String.t()} def in_english(number) do end end diff --git a/exercises/say/say_test.exs b/exercises/say/say_test.exs index 3e07d6fe62..deb1ff3c6e 100644 --- a/exercises/say/say_test.exs +++ b/exercises/say/say_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("say.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule SayTest do use ExUnit.Case @@ -70,7 +70,9 @@ defmodule SayTest do @tag :pending test "a big number" do - assert Say.in_english(987_654_321_123) == {:ok, "nine hundred eighty-seven billion six hundred fifty-four million three hundred twenty-one thousand one hundred twenty-three"} + assert Say.in_english(987_654_321_123) == + {:ok, + "nine hundred eighty-seven billion six hundred fifty-four million three hundred twenty-one thousand one hundred twenty-three"} end @tag :pending diff --git a/exercises/scale-generator/example.exs b/exercises/scale-generator/example.exs index a6739bda30..6413936e8e 100644 --- a/exercises/scale-generator/example.exs +++ b/exercises/scale-generator/example.exs @@ -17,7 +17,8 @@ defmodule ScaleGenerator do "M": E "A": F """ - @spec step(scale :: list(String.t()), tonic :: String.t(), step :: String.t()) :: list(String.t()) + @spec step(scale :: list(String.t()), tonic :: String.t(), step :: String.t()) :: + list(String.t()) def step(scale, tonic, step) do scale |> rotate_chromatic(tonic) |> do_step(step) end @@ -66,13 +67,17 @@ defmodule ScaleGenerator do scale_length = length(scale) scale - |> Stream.cycle + |> Stream.cycle() |> Enum.take(2 * scale_length) - |> rotate_chromatic(tonic |> String.capitalize, []) + |> rotate_chromatic(tonic |> String.capitalize(), []) |> Enum.take(scale_length + 1) end - defp rotate_chromatic([tonic | _] = scale_from_tonic, tonic, results), do: scale_from_tonic ++ results - defp rotate_chromatic([head | tail], tonic, results), do: rotate_chromatic(tail, tonic, results ++ [head]) + + defp rotate_chromatic([tonic | _] = scale_from_tonic, tonic, results), + do: scale_from_tonic ++ results + + defp rotate_chromatic([head | tail], tonic, results), + do: rotate_chromatic(tail, tonic, results ++ [head]) @doc """ Certain scales will require the use of the flat version, depending on the @@ -86,8 +91,10 @@ defmodule ScaleGenerator do """ @spec find_chromatic_scale(tonic :: String.t()) :: list(String.t()) for flat_tonic <- @flat_keys do - def find_chromatic_scale(unquote(flat_tonic)), do: flat_chromatic_scale(unquote(flat_tonic |> String.capitalize)) + def find_chromatic_scale(unquote(flat_tonic)), + do: flat_chromatic_scale(unquote(flat_tonic |> String.capitalize())) end + def find_chromatic_scale(tonic) do chromatic_scale(tonic) end @@ -107,13 +114,17 @@ defmodule ScaleGenerator do def scale(tonic, pattern) do tonic |> find_chromatic_scale - |> generate_scale(pattern, [tonic |> String.capitalize]) + |> generate_scale(pattern, [tonic |> String.capitalize()]) end defp generate_scale(scale, pattern, results) defp generate_scale(_scale, "", results), do: Enum.reverse(results) - defp generate_scale(scale, <>, [last_tonic | _] = results) do + + defp generate_scale( + scale, + <>, + [last_tonic | _] = results + ) do generate_scale(scale, pattern, [step(scale, last_tonic, step_amt) | results]) end end - diff --git a/exercises/scale-generator/scale_generator.exs b/exercises/scale-generator/scale_generator.exs index cddc7649f6..b093d0ed5f 100644 --- a/exercises/scale-generator/scale_generator.exs +++ b/exercises/scale-generator/scale_generator.exs @@ -13,7 +13,8 @@ defmodule ScaleGenerator do "M": E "A": F """ - @spec step(scale :: list(String.t()), tonic :: String.t(), step :: String.t()) :: list(String.t()) + @spec step(scale :: list(String.t()), tonic :: String.t(), step :: String.t()) :: + list(String.t()) def step(scale, tonic, step) do end @@ -80,4 +81,3 @@ defmodule ScaleGenerator do def scale(tonic, pattern) do end end - diff --git a/exercises/scale-generator/scale_generator_test.exs b/exercises/scale-generator/scale_generator_test.exs index 0e903b3a81..79881ad4f2 100644 --- a/exercises/scale-generator/scale_generator_test.exs +++ b/exercises/scale-generator/scale_generator_test.exs @@ -2,28 +2,28 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("scale_generator.exs", __DIR__) end -ExUnit.start -ExUnit.configure trace: true, exclude: :pending +ExUnit.start() +ExUnit.configure(trace: true, exclude: :pending) defmodule ScaleGeneratorTest do use ExUnit.Case - @major_scale_pattern "MMmMMMm" - @minor_scale_pattern "MmMMmMM" - @dorian_scale_pattern "MmMMMmM" - @mixolydian_scale_pattern "MMmMMmM" - @lydian_scale_pattern "MMMmMMm" - @phrygian_scale_pattern "mMMMmMM" - @locrian_scale_pattern "mMMmMMM" - @harmonic_minor_scale_pattern "MmMMmAm" - @melodic_minor_scale_pattern "MmMMMMm" - @octatonic_scale_pattern "MmMmMmMm" - @hexatonic_scale_pattern "MMMMMM" - @pentatonic_scale_pattern "MMAMA" - @enigmatic_scale_pattern "mAMMMmm" + @major_scale_pattern "MMmMMMm" + @minor_scale_pattern "MmMMmMM" + @dorian_scale_pattern "MmMMMmM" + @mixolydian_scale_pattern "MMmMMmM" + @lydian_scale_pattern "MMMmMMm" + @phrygian_scale_pattern "mMMMmMM" + @locrian_scale_pattern "mMMmMMM" + @harmonic_minor_scale_pattern "MmMMmAm" + @melodic_minor_scale_pattern "MmMMMMm" + @octatonic_scale_pattern "MmMmMmMm" + @hexatonic_scale_pattern "MMMMMM" + @pentatonic_scale_pattern "MMAMA" + @enigmatic_scale_pattern "mAMMMmm" describe "step to next note" do - #@tag :pending + # @tag :pending test "with half-tone interval" do assert ScaleGenerator.step(~w(C C# D D# E F F# G G# A A# B), "C", "m") == "C#" end @@ -279,4 +279,3 @@ defmodule ScaleGeneratorTest do end end end - diff --git a/exercises/scrabble-score/scrabble.exs b/exercises/scrabble-score/scrabble.exs index 0204ddd20c..900c25b7ff 100644 --- a/exercises/scrabble-score/scrabble.exs +++ b/exercises/scrabble-score/scrabble.exs @@ -2,8 +2,7 @@ defmodule Scrabble do @doc """ Calculate the scrabble score for the word. """ - @spec score(String.t) :: non_neg_integer + @spec score(String.t()) :: non_neg_integer def score(word) do - end end diff --git a/exercises/scrabble-score/scrabble_score_test.exs b/exercises/scrabble-score/scrabble_score_test.exs index 11071da00b..9d969c8131 100644 --- a/exercises/scrabble-score/scrabble_score_test.exs +++ b/exercises/scrabble-score/scrabble_score_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("scrabble.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule ScrabbleScoreTest do use ExUnit.Case diff --git a/exercises/secret-handshake/example.exs b/exercises/secret-handshake/example.exs index 0fefcb0282..71f346abd1 100644 --- a/exercises/secret-handshake/example.exs +++ b/exercises/secret-handshake/example.exs @@ -20,8 +20,8 @@ defmodule SecretHandshake do @spec commands(code :: integer) :: list(String.t()) def commands(code) do @codes - |> Enum.with_index - |> Enum.map(fn {command, i} -> { command, 2 <<< (i-1) } end) + |> Enum.with_index() + |> Enum.map(fn {command, i} -> {command, 2 <<< (i - 1)} end) |> decode_commands(code, []) end @@ -31,7 +31,8 @@ defmodule SecretHandshake do _ -> Enum.reverse(results) end end - defp decode_commands([{ command, flag } | flags], code, results) do + + defp decode_commands([{command, flag} | flags], code, results) do case flag_set(code, flag) do true -> decode_commands(flags, code, [command | results]) _ -> decode_commands(flags, code, results) @@ -40,4 +41,3 @@ defmodule SecretHandshake do defp flag_set(flags, flag_to_check), do: (flags &&& flag_to_check) == flag_to_check end - diff --git a/exercises/secret-handshake/secret_handshake.exs b/exercises/secret-handshake/secret_handshake.exs index acdc900753..c0075c6d0f 100644 --- a/exercises/secret-handshake/secret_handshake.exs +++ b/exercises/secret-handshake/secret_handshake.exs @@ -17,4 +17,3 @@ defmodule SecretHandshake do def commands(code) do end end - diff --git a/exercises/secret-handshake/secret_handshake_test.exs b/exercises/secret-handshake/secret_handshake_test.exs index e560b8df7d..bca52eecd3 100644 --- a/exercises/secret-handshake/secret_handshake_test.exs +++ b/exercises/secret-handshake/secret_handshake_test.exs @@ -2,14 +2,14 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("secret_handshake.exs", __DIR__) end -ExUnit.start -ExUnit.configure trace: true, exclude: :pending +ExUnit.start() +ExUnit.configure(trace: true, exclude: :pending) defmodule SecretHandshakeTest do use ExUnit.Case describe "Create a handshake for a number" do - #@tag :pending + # @tag :pending test "wink for 1" do assert SecretHandshake.commands(1) == ["wink"] end diff --git a/exercises/series/example.exs b/exercises/series/example.exs index a1e8ad5103..2a33472bd4 100644 --- a/exercises/series/example.exs +++ b/exercises/series/example.exs @@ -6,8 +6,8 @@ defmodule StringSeries do """ @spec slices(s :: String.t(), size :: integer) :: list(String.t()) def slices(_s, size) when size < 1, do: [] + def slices(s, size) do - s |> String.graphemes |> Enum.chunk(size, 1) |> Enum.map(&Enum.join/1) + s |> String.graphemes() |> Enum.chunk(size, 1) |> Enum.map(&Enum.join/1) end end - diff --git a/exercises/series/series.exs b/exercises/series/series.exs index 19aa0d5b04..19f6400ce1 100644 --- a/exercises/series/series.exs +++ b/exercises/series/series.exs @@ -8,4 +8,3 @@ defmodule StringSeries do def slices(_s, _size) do end end - diff --git a/exercises/series/series_test.exs b/exercises/series/series_test.exs index 999b717d04..a20e9e26ea 100644 --- a/exercises/series/series_test.exs +++ b/exercises/series/series_test.exs @@ -2,13 +2,13 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("series.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule StringSeriesTest do use ExUnit.Case - #@tag :pending + # @tag :pending test "slices of size 1" do assert StringSeries.slices("01234", 1) == ["0", "1", "2", "3", "4"] end @@ -50,4 +50,3 @@ defmodule StringSeriesTest do assert StringSeries.slices("01234", 0) == [] end end - diff --git a/exercises/sieve/example.exs b/exercises/sieve/example.exs index d51575a6ac..d0d6ea376d 100644 --- a/exercises/sieve/example.exs +++ b/exercises/sieve/example.exs @@ -1,17 +1,16 @@ defmodule Sieve do - @doc """ Generates a list of primes up to a given limit. """ @spec primes_to(non_neg_integer) :: [non_neg_integer] def primes_to(limit) do - Enum.to_list(2..limit) |> do_primes([]) |> Enum.reverse + Enum.to_list(2..limit) |> do_primes([]) |> Enum.reverse() end defp do_primes([], primes), do: primes - defp do_primes([ candidate | rest ], primes) do + + defp do_primes([candidate | rest], primes) do candidates = Enum.reject(rest, &(rem(&1, candidate) == 0)) - do_primes(candidates, [ candidate | primes ]) + do_primes(candidates, [candidate | primes]) end - end diff --git a/exercises/sieve/sieve.exs b/exercises/sieve/sieve.exs index 70837431e0..e35cb139f1 100644 --- a/exercises/sieve/sieve.exs +++ b/exercises/sieve/sieve.exs @@ -1,11 +1,8 @@ defmodule Sieve do - @doc """ Generates a list of primes up to a given limit. """ @spec primes_to(non_neg_integer) :: [non_neg_integer] def primes_to(limit) do - end - end diff --git a/exercises/sieve/sieve_test.exs b/exercises/sieve/sieve_test.exs index 52030dd22f..694784f682 100644 --- a/exercises/sieve/sieve_test.exs +++ b/exercises/sieve/sieve_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("sieve.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule SieveTest do use ExUnit.Case @@ -15,25 +15,177 @@ defmodule SieveTest do @tag :pending test "primes to 1000" do - result = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, - 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, - 89, 97, 101, 103, 107, 109, 113, 127, 131, - 137, 139, 149, 151, 157, 163, 167, 173, 179, - 181, 191, 193, 197, 199, 211, 223, 227, 229, - 233, 239, 241, 251, 257, 263, 269, 271, 277, - 281, 283, 293, 307, 311, 313, 317, 331, 337, - 347, 349, 353, 359, 367, 373, 379, 383, 389, - 397, 401, 409, 419, 421, 431, 433, 439, 443, - 449, 457, 461, 463, 467, 479, 487, 491, 499, - 503, 509, 521, 523, 541, 547, 557, 563, 569, - 571, 577, 587, 593, 599, 601, 607, 613, 617, - 619, 631, 641, 643, 647, 653, 659, 661, 673, - 677, 683, 691, 701, 709, 719, 727, 733, 739, - 743, 751, 757, 761, 769, 773, 787, 797, 809, - 811, 821, 823, 827, 829, 839, 853, 857, 859, - 863, 877, 881, 883, 887, 907, 911, 919, 929, - 937, 941, 947, 953, 967, 971, 977, 983, 991, 997] + result = [ + 2, + 3, + 5, + 7, + 11, + 13, + 17, + 19, + 23, + 29, + 31, + 37, + 41, + 43, + 47, + 53, + 59, + 61, + 67, + 71, + 73, + 79, + 83, + 89, + 97, + 101, + 103, + 107, + 109, + 113, + 127, + 131, + 137, + 139, + 149, + 151, + 157, + 163, + 167, + 173, + 179, + 181, + 191, + 193, + 197, + 199, + 211, + 223, + 227, + 229, + 233, + 239, + 241, + 251, + 257, + 263, + 269, + 271, + 277, + 281, + 283, + 293, + 307, + 311, + 313, + 317, + 331, + 337, + 347, + 349, + 353, + 359, + 367, + 373, + 379, + 383, + 389, + 397, + 401, + 409, + 419, + 421, + 431, + 433, + 439, + 443, + 449, + 457, + 461, + 463, + 467, + 479, + 487, + 491, + 499, + 503, + 509, + 521, + 523, + 541, + 547, + 557, + 563, + 569, + 571, + 577, + 587, + 593, + 599, + 601, + 607, + 613, + 617, + 619, + 631, + 641, + 643, + 647, + 653, + 659, + 661, + 673, + 677, + 683, + 691, + 701, + 709, + 719, + 727, + 733, + 739, + 743, + 751, + 757, + 761, + 769, + 773, + 787, + 797, + 809, + 811, + 821, + 823, + 827, + 829, + 839, + 853, + 857, + 859, + 863, + 877, + 881, + 883, + 887, + 907, + 911, + 919, + 929, + 937, + 941, + 947, + 953, + 967, + 971, + 977, + 983, + 991, + 997 + ] + assert Sieve.primes_to(1000) == result end - end diff --git a/exercises/simple-cipher/example.exs b/exercises/simple-cipher/example.exs index 93cdfdcc33..f3ef611134 100644 --- a/exercises/simple-cipher/example.exs +++ b/exercises/simple-cipher/example.exs @@ -1,13 +1,14 @@ defmodule SimpleCipher do - @alphabet "abcdefghijklmnopqrstuvwxyz" |> String.graphemes + @alphabet "abcdefghijklmnopqrstuvwxyz" |> String.graphemes() @alphabet_size @alphabet |> length for key_char <- @alphabet do - shifted_alphabet = Stream.cycle(@alphabet) - |> Stream.drop_while(&(&1 != key_char)) - |> Enum.take(@alphabet_size) + shifted_alphabet = + Stream.cycle(@alphabet) + |> Stream.drop_while(&(&1 != key_char)) + |> Enum.take(@alphabet_size) - for { plain, cipher } <- Enum.zip(@alphabet, shifted_alphabet) do + for {plain, cipher} <- Enum.zip(@alphabet, shifted_alphabet) do defp encode_char(unquote(plain), unquote(key_char)), do: unquote(cipher) defp decode_char(unquote(cipher), unquote(key_char)), do: unquote(plain) end @@ -69,12 +70,11 @@ defmodule SimpleCipher do end defp convert_keystream(text, key, converter) do - keystream = key |> String.graphemes |> Stream.cycle + keystream = key |> String.graphemes() |> Stream.cycle() text - |> String.graphemes + |> String.graphemes() |> Enum.zip(keystream) |> Enum.map_join(converter) end end - diff --git a/exercises/simple-cipher/simple_cipher.exs b/exercises/simple-cipher/simple_cipher.exs index 278d2807e8..0355e0a4f3 100644 --- a/exercises/simple-cipher/simple_cipher.exs +++ b/exercises/simple-cipher/simple_cipher.exs @@ -46,4 +46,3 @@ defmodule SimpleCipher do def decode(ciphertext, key) do end end - diff --git a/exercises/simple-cipher/simple_cipher_test.exs b/exercises/simple-cipher/simple_cipher_test.exs index 21b10c9396..c04d31a13a 100644 --- a/exercises/simple-cipher/simple_cipher_test.exs +++ b/exercises/simple-cipher/simple_cipher_test.exs @@ -2,13 +2,13 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("simple_cipher.exs", __DIR__) end -ExUnit.start -ExUnit.configure trace: true, exclude: :pending +ExUnit.start() +ExUnit.configure(trace: true, exclude: :pending) defmodule SimpleCipherTest do use ExUnit.Case - #@tag :pending + # @tag :pending test "encoding with 'a' returns the original text" do assert SimpleCipher.encode("a", "a") == "a" assert SimpleCipher.encode("b", "a") == "b" @@ -86,4 +86,3 @@ defmodule SimpleCipherTest do assert SimpleCipher.decode(ciphertext, plaintext) == key end end - diff --git a/exercises/simple-linked-list/example.exs b/exercises/simple-linked-list/example.exs index 08d334fb9b..fb2b135880 100644 --- a/exercises/simple-linked-list/example.exs +++ b/exercises/simple-linked-list/example.exs @@ -71,8 +71,9 @@ defmodule LinkedList do def to_list(list) do list |> do_to_list([]) |> Enum.reverse() end + defp do_to_list({}, acc), do: acc - defp do_to_list({h, t}, acc), do: do_to_list(t, [h|acc]) + defp do_to_list({h, t}, acc), do: do_to_list(t, [h | acc]) @doc """ Reverse a LinkedList @@ -81,6 +82,7 @@ defmodule LinkedList do def reverse(list) do do_reverse(list, new()) end + def do_reverse({}, acc), do: acc def do_reverse({h, t}, acc), do: do_reverse(t, push(acc, h)) end diff --git a/exercises/simple-linked-list/linked_list_test.exs b/exercises/simple-linked-list/linked_list_test.exs index 810eeeadc5..4a8f4dd169 100644 --- a/exercises/simple-linked-list/linked_list_test.exs +++ b/exercises/simple-linked-list/linked_list_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("linked_list.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule LinkedListTest do use ExUnit.Case @@ -62,6 +62,7 @@ defmodule LinkedListTest do LinkedList.new() |> LinkedList.push(:a) |> LinkedList.push(:b) + assert LinkedList.peek(list) == {:ok, :b} assert {:ok, list} = LinkedList.tail(list) assert LinkedList.peek(list) == {:ok, :a} @@ -145,10 +146,12 @@ defmodule LinkedListTest do @tag :pending test "reverse/1 round trip" do list = Enum.to_list(1..200) + linked_list = LinkedList.from_list(list) |> LinkedList.reverse() |> LinkedList.reverse() + assert LinkedList.to_list(linked_list) == list end end diff --git a/exercises/space-age/example.exs b/exercises/space-age/example.exs index 7fcd4f47f7..fcaee3b5b2 100644 --- a/exercises/space-age/example.exs +++ b/exercises/space-age/example.exs @@ -1,13 +1,12 @@ defmodule SpaceAge do - - def age_on(:earth, seconds), do: seconds / 31557600.0 + def age_on(:earth, seconds), do: seconds / 31_557_600.0 def age_on(planet, seconds), do: age_on(:earth, seconds) / planet_rel_years(planet) defp planet_rel_years(:mercury), do: 0.2408467 - defp planet_rel_years(:venus), do: 0.61519726 - defp planet_rel_years(:mars), do: 1.8808158 + defp planet_rel_years(:venus), do: 0.61519726 + defp planet_rel_years(:mars), do: 1.8808158 defp planet_rel_years(:jupiter), do: 11.862615 - defp planet_rel_years(:saturn), do: 29.447498 - defp planet_rel_years(:uranus), do: 84.016846 + defp planet_rel_years(:saturn), do: 29.447498 + defp planet_rel_years(:uranus), do: 84.016846 defp planet_rel_years(:neptune), do: 164.79132 end diff --git a/exercises/space-age/space_age.exs b/exercises/space-age/space_age.exs index 33c975703a..6a87a2b6b0 100644 --- a/exercises/space-age/space_age.exs +++ b/exercises/space-age/space_age.exs @@ -1,6 +1,13 @@ defmodule SpaceAge do - @type planet :: :mercury | :venus | :earth | :mars | :jupiter - | :saturn | :uranus | :neptune + @type planet :: + :mercury + | :venus + | :earth + | :mars + | :jupiter + | :saturn + | :uranus + | :neptune @doc """ Return the number of years a person that has lived for 'seconds' seconds is @@ -8,6 +15,5 @@ defmodule SpaceAge do """ @spec age_on(planet, pos_integer) :: float def age_on(planet, seconds) do - end end diff --git a/exercises/space-age/space_age_test.exs b/exercises/space-age/space_age_test.exs index 4119a69a67..130b5335f1 100644 --- a/exercises/space-age/space_age_test.exs +++ b/exercises/space-age/space_age_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("space_age.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) # You need to define a SpaceAge module containing a function age_on that given a # planet (:earth, :saturn, etc) and a number of seconds returns the age in years diff --git a/exercises/spiral-matrix/example.exs b/exercises/spiral-matrix/example.exs index 5d432c1996..95a35b154c 100644 --- a/exercises/spiral-matrix/example.exs +++ b/exercises/spiral-matrix/example.exs @@ -1,19 +1,24 @@ defmodule Spiral do - @doc """ Given the dimension, return a square matrix of numbers in clockwise spiral order. """ @spec matrix(dimension :: integer) :: list(list(integer)) def matrix(0), do: [] + def matrix(dimension) do unwind(dimension, dimension, 1) end defp unwind(row, col, start) do case col do - 0 -> [[]] - _ -> [Enum.to_list(start..start + col - 1) | - unwind(col, row - 1, start + col) |> rotate_right] + 0 -> + [[]] + + _ -> + [ + Enum.to_list(start..(start + col - 1)) + | unwind(col, row - 1, start + col) |> rotate_right + ] end end @@ -22,6 +27,6 @@ defmodule Spiral do end defp transpose(matrix) do - matrix |> List.zip |> Enum.map(&Tuple.to_list/1) + matrix |> List.zip() |> Enum.map(&Tuple.to_list/1) end end diff --git a/exercises/spiral-matrix/spiral.exs b/exercises/spiral-matrix/spiral.exs index 3e2bdb5c01..41fe188e28 100644 --- a/exercises/spiral-matrix/spiral.exs +++ b/exercises/spiral-matrix/spiral.exs @@ -1,5 +1,4 @@ defmodule Spiral do - @doc """ Given the dimension, return a square matrix of numbers in clockwise spiral order. """ diff --git a/exercises/spiral-matrix/spiral_test.exs b/exercises/spiral-matrix/spiral_test.exs index f57464eb5b..ca448449fe 100644 --- a/exercises/spiral-matrix/spiral_test.exs +++ b/exercises/spiral-matrix/spiral_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("spiral.exs", __DIR__) end -ExUnit.start -ExUnit.configure trace: true, exclude: :pending +ExUnit.start() +ExUnit.configure(trace: true, exclude: :pending) defmodule SpiralTest do use ExUnit.Case @@ -15,44 +15,44 @@ defmodule SpiralTest do @tag :pending test "trivial spiral" do - assert Spiral.matrix(1) == [ [1] ] + assert Spiral.matrix(1) == [[1]] end @tag :pending test "spiral of side length 2" do assert Spiral.matrix(2) == [ - [1, 2], - [4, 3] - ] + [1, 2], + [4, 3] + ] end @tag :pending test "spiral of side length 3" do assert Spiral.matrix(3) == [ - [1, 2, 3], - [8, 9, 4], - [7, 6, 5] - ] + [1, 2, 3], + [8, 9, 4], + [7, 6, 5] + ] end @tag :pending test "spiral of side length 4" do assert Spiral.matrix(4) == [ - [ 1, 2, 3, 4], - [12, 13, 14, 5], - [11, 16, 15, 6], - [10, 9, 8, 7] - ] + [1, 2, 3, 4], + [12, 13, 14, 5], + [11, 16, 15, 6], + [10, 9, 8, 7] + ] end @tag :pending test "spiral of size 5" do assert Spiral.matrix(5) == [ - [ 1, 2, 3, 4, 5], - [16, 17, 18, 19, 6], - [15, 24, 25, 20, 7], - [14, 23, 22, 21, 8], - [13, 12, 11, 10, 9] - ] + [1, 2, 3, 4, 5], + [16, 17, 18, 19, 6], + [15, 24, 25, 20, 7], + [14, 23, 22, 21, 8], + [13, 12, 11, 10, 9] + ] end end diff --git a/exercises/strain/example.exs b/exercises/strain/example.exs index 76c2f530ac..be3744312f 100644 --- a/exercises/strain/example.exs +++ b/exercises/strain/example.exs @@ -5,12 +5,13 @@ defmodule Strain do Do not use `Enum.filter`. """ - @spec keep(list :: list(any), fun :: ((any) -> boolean)) :: list(any) + @spec keep(list :: list(any), fun :: (any -> boolean)) :: list(any) def keep(list, fun) do do_keep(list, fun, []) end defp do_keep([], _, results), do: Enum.reverse(results) + defp do_keep([head | tail], fun, results) do case apply(fun, [head]) do true -> do_keep(tail, fun, [head | results]) @@ -24,17 +25,17 @@ defmodule Strain do Do not use `Enum.reject`. """ - @spec discard(list :: list(any), fun :: ((any) -> boolean)) :: list(any) + @spec discard(list :: list(any), fun :: (any -> boolean)) :: list(any) def discard(list, fun) do do_discard(list, fun, []) end defp do_discard([], _, results), do: Enum.reverse(results) + defp do_discard([head | tail], fun, results) do case apply(fun, [head]) do true -> do_discard(tail, fun, results) - _ -> do_discard(tail, fun, [ head | results ]) + _ -> do_discard(tail, fun, [head | results]) end end end - diff --git a/exercises/strain/strain.exs b/exercises/strain/strain.exs index 52b3c04d64..187d742b3c 100644 --- a/exercises/strain/strain.exs +++ b/exercises/strain/strain.exs @@ -5,7 +5,7 @@ defmodule Strain do Do not use `Enum.filter`. """ - @spec keep(list :: list(any), fun :: ((any) -> boolean)) :: list(any) + @spec keep(list :: list(any), fun :: (any -> boolean)) :: list(any) def keep(list, fun) do end @@ -15,7 +15,7 @@ defmodule Strain do Do not use `Enum.reject`. """ - @spec discard(list :: list(any), fun :: ((any) -> boolean)) :: list(any) + @spec discard(list :: list(any), fun :: (any -> boolean)) :: list(any) def discard(list, fun) do end end diff --git a/exercises/strain/strain_test.exs b/exercises/strain/strain_test.exs index 6da0330bf9..0c15d3c081 100644 --- a/exercises/strain/strain_test.exs +++ b/exercises/strain/strain_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("strain.exs", __DIR__) end -ExUnit.start -ExUnit.configure trace: true, exclude: :pending +ExUnit.start() +ExUnit.configure(trace: true, exclude: :pending) defmodule StrainTest do use ExUnit.Case @@ -12,7 +12,7 @@ defmodule StrainTest do defp is_even?(n), do: rem(n, 2) == 0 defp noop(_), do: true - #@tag :pending + # @tag :pending test "empty keep" do assert Strain.keep([], &noop/1) == [] end @@ -35,7 +35,7 @@ defmodule StrainTest do @tag :pending test "keep strings" do words = ~w(apple zebra banana zombies cherimoya zelot) - assert Strain.keep(words, &(String.starts_with?(&1, "z"))) == ~w(zebra zombies zelot) + assert Strain.keep(words, &String.starts_with?(&1, "z")) == ~w(zebra zombies zelot) end @tag :pending @@ -50,7 +50,12 @@ defmodule StrainTest do [1, 2, 5] ] - assert Strain.keep(rows, fn row -> 5 in row end) == [[5, 5, 5], [5, 1, 2], [1, 5, 2], [1, 2, 5]] + assert Strain.keep(rows, fn row -> 5 in row end) == [ + [5, 5, 5], + [5, 1, 2], + [1, 5, 2], + [1, 2, 5] + ] end @tag :pending @@ -76,7 +81,7 @@ defmodule StrainTest do @tag :pending test "discard strings" do words = ~w(apple zebra banana zombies cherimoya zelot) - assert Strain.discard(words, &(String.starts_with?(&1, "z"))) == ~w(apple banana cherimoya) + assert Strain.discard(words, &String.starts_with?(&1, "z")) == ~w(apple banana cherimoya) end @tag :pending @@ -90,7 +95,7 @@ defmodule StrainTest do [2, 2, 1], [1, 2, 5] ] + assert Strain.discard(rows, fn row -> 5 in row end) == [[1, 2, 3], [2, 1, 2], [2, 2, 1]] end end - diff --git a/exercises/sublist/example.exs b/exercises/sublist/example.exs index 1dde8cbc50..8532b10e73 100644 --- a/exercises/sublist/example.exs +++ b/exercises/sublist/example.exs @@ -4,27 +4,31 @@ defmodule Sublist do and if not whether it is equal or unequal to the second list. """ def compare(a, b) do - case { length(a), length(b) } do - { la, lb } when la < lb -> + case {length(a), length(b)} do + {la, lb} when la < lb -> if is_sublist(a, b, la, lb), do: :sublist, else: :unequal - { la, lb } when la > lb -> + + {la, lb} when la > lb -> if is_sublist(b, a, lb, la), do: :superlist, else: :unequal + _ -> if a == b, do: :equal, else: :unequal end end defp is_sublist(_, _, len_a, len_b) when len_a > len_b, do: false - defp is_sublist([], _, _, _), do: true # empty is sublist of all non-empty - defp is_sublist(a, b=[_|t], len_a, len_b) do + # empty is sublist of all non-empty + defp is_sublist([], _, _, _), do: true + + defp is_sublist(a, b = [_ | t], len_a, len_b) do if try_is_sublist(a, b) do true else - is_sublist(a, t, len_a, len_b-1) + is_sublist(a, t, len_a, len_b - 1) end end defp try_is_sublist([], _), do: true - defp try_is_sublist([x|at], [x|bt]), do: try_is_sublist(at, bt) + defp try_is_sublist([x | at], [x | bt]), do: try_is_sublist(at, bt) defp try_is_sublist(_, _), do: false end diff --git a/exercises/sublist/sublist.exs b/exercises/sublist/sublist.exs index b0097fb4ef..b490ec72c0 100644 --- a/exercises/sublist/sublist.exs +++ b/exercises/sublist/sublist.exs @@ -4,6 +4,5 @@ defmodule Sublist do and if not whether it is equal or unequal to the second list. """ def compare(a, b) do - end end diff --git a/exercises/sublist/sublist_test.exs b/exercises/sublist/sublist_test.exs index 9af7e713d9..1f3e061a35 100644 --- a/exercises/sublist/sublist_test.exs +++ b/exercises/sublist/sublist_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("sublist.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule SublistTest do use ExUnit.Case @@ -35,64 +35,62 @@ defmodule SublistTest do @tag :pending test "sublist at start" do - assert Sublist.compare([1,2,3],[1,2,3,4,5]) == :sublist + assert Sublist.compare([1, 2, 3], [1, 2, 3, 4, 5]) == :sublist end @tag :pending test "sublist in middle" do - assert Sublist.compare([4,3,2],[5,4,3,2,1]) == :sublist + assert Sublist.compare([4, 3, 2], [5, 4, 3, 2, 1]) == :sublist end @tag :pending test "sublist at end" do - assert Sublist.compare([3,4,5],[1,2,3,4,5]) == :sublist + assert Sublist.compare([3, 4, 5], [1, 2, 3, 4, 5]) == :sublist end @tag :pending test "partially matching sublist at start" do - assert Sublist.compare([1,1,2], [1,1,1,2]) == :sublist + assert Sublist.compare([1, 1, 2], [1, 1, 1, 2]) == :sublist end @tag :pending test "sublist early in huge list" do - assert Sublist.compare([3,4,5], Enum.to_list(1..1_000_000)) == :sublist + assert Sublist.compare([3, 4, 5], Enum.to_list(1..1_000_000)) == :sublist end @tag :pending test "huge sublist not in huge list" do - assert Sublist.compare(Enum.to_list(10..1_000_001), - Enum.to_list(1..1_000_000)) - == :unequal + assert Sublist.compare(Enum.to_list(10..1_000_001), Enum.to_list(1..1_000_000)) == :unequal end @tag :pending test "superlist at start" do - assert Sublist.compare([1,2,3,4,5],[1,2,3]) == :superlist + assert Sublist.compare([1, 2, 3, 4, 5], [1, 2, 3]) == :superlist end @tag :pending test "superlist in middle" do - assert Sublist.compare([5,4,3,2,1],[4,3,2]) == :superlist + assert Sublist.compare([5, 4, 3, 2, 1], [4, 3, 2]) == :superlist end @tag :pending test "superlist at end" do - assert Sublist.compare([1,2,3,4,5],[3,4,5]) == :superlist + assert Sublist.compare([1, 2, 3, 4, 5], [3, 4, 5]) == :superlist end @tag :pending test "1 and 2 does not contain 3" do - assert Sublist.compare([1,2], [3]) == :unequal + assert Sublist.compare([1, 2], [3]) == :unequal end @tag :pending test "partially matching superlist at start" do - assert Sublist.compare([1,1,1,2], [1,1,2]) == :superlist + assert Sublist.compare([1, 1, 1, 2], [1, 1, 2]) == :superlist end @tag :pending test "superlist early in huge list" do - assert Sublist.compare(Enum.to_list(1..1_000_000), [3,4,5]) == :superlist + assert Sublist.compare(Enum.to_list(1..1_000_000), [3, 4, 5]) == :superlist end @tag :pending @@ -102,11 +100,11 @@ defmodule SublistTest do @tag :pending test "recurring values sublist" do - assert Sublist.compare([1,2,1,2,3], [1,2,3,1,2,1,2,3,2,1]) == :sublist + assert Sublist.compare([1, 2, 1, 2, 3], [1, 2, 3, 1, 2, 1, 2, 3, 2, 1]) == :sublist end @tag :pending test "recurring values unequal" do - assert Sublist.compare([1,2,1,2,3], [1,2,3,1,2,3,2,3,2,1]) == :unequal + assert Sublist.compare([1, 2, 1, 2, 3], [1, 2, 3, 1, 2, 3, 2, 3, 2, 1]) == :unequal end end diff --git a/exercises/sum-of-multiples/example.exs b/exercises/sum-of-multiples/example.exs index f7f5be77fb..1726e4c678 100644 --- a/exercises/sum-of-multiples/example.exs +++ b/exercises/sum-of-multiples/example.exs @@ -1,12 +1,11 @@ defmodule SumOfMultiples do - @doc """ Adds up all numbers from 1 to a given end number that are multiples of the factors provided. """ @spec to(non_neg_integer, [non_neg_integer]) :: non_neg_integer def to(limit, factors) do - Enum.reduce(1..limit-1, 0, fn(n, acc) -> - if Enum.any?(factors, &(rem(n, &1) == 0)), do: acc + n, else: acc end) + Enum.reduce(1..(limit - 1), 0, fn n, acc -> + if Enum.any?(factors, &(rem(n, &1) == 0)), do: acc + n, else: acc + end) end - end diff --git a/exercises/sum-of-multiples/sum_of_multiples.exs b/exercises/sum-of-multiples/sum_of_multiples.exs index f96cc6f609..f589149dea 100644 --- a/exercises/sum-of-multiples/sum_of_multiples.exs +++ b/exercises/sum-of-multiples/sum_of_multiples.exs @@ -4,6 +4,5 @@ defmodule SumOfMultiples do """ @spec to(non_neg_integer, [non_neg_integer]) :: non_neg_integer def to(limit, factors) do - end end diff --git a/exercises/sum-of-multiples/sum_of_multiples_test.exs b/exercises/sum-of-multiples/sum_of_multiples_test.exs index 7753fdead3..0ed8d440dd 100644 --- a/exercises/sum-of-multiples/sum_of_multiples_test.exs +++ b/exercises/sum-of-multiples/sum_of_multiples_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("sum_of_multiples.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule SumOfMultiplesTest do use ExUnit.Case @@ -35,7 +35,7 @@ defmodule SumOfMultiplesTest do @tag :pending test "sum to 1000" do - assert SumOfMultiples.to(1000, [3, 5]) == 233168 + assert SumOfMultiples.to(1000, [3, 5]) == 233_168 end @tag :pending @@ -59,6 +59,6 @@ defmodule SumOfMultiplesTest do @tag :pending test "configurable 43, 47 to 10000" do multiples = [43, 47] - assert SumOfMultiples.to(10000, multiples) == 2203160 + assert SumOfMultiples.to(10000, multiples) == 2_203_160 end end diff --git a/exercises/test_helper.exs b/exercises/test_helper.exs index d61e2db6fb..8911d5d321 100644 --- a/exercises/test_helper.exs +++ b/exercises/test_helper.exs @@ -1,7 +1,7 @@ "exercises/**/example.exs" -|> Path.wildcard -|> Kernel.ParallelRequire.files +|> Path.wildcard() +|> Kernel.ParallelRequire.files() System.put_env("EXERCISM_TEST_EXAMPLES", "true") -ExUnit.configure include: :pending -ExUnit.start +ExUnit.configure(include: :pending) +ExUnit.start() diff --git a/exercises/tournament/example.exs b/exercises/tournament/example.exs index ced7628484..01b4a72001 100644 --- a/exercises/tournament/example.exs +++ b/exercises/tournament/example.exs @@ -1,6 +1,6 @@ defmodule Tournament do - @stats_header { "Team", "MP", "W", "D", "L", "P" } - @initial_stats { 0, 0, 0, 0, 0 } + @stats_header {"Team", "MP", "W", "D", "L", "P"} + @initial_stats {0, 0, 0, 0, 0} @doc """ Given `input` lines representing two teams and whether the first of them won, @@ -24,6 +24,7 @@ defmodule Tournament do end defp do_tally(results, []), do: results + defp do_tally(results, [line | rest]) do results |> parse_line(line |> String.split(";", trim: true)) @@ -45,26 +46,32 @@ defmodule Tournament do defp parse_line(results, _), do: results defp mark_win(results, team) do - { played, wins, draws, lost, points } = Map.get(results, team, @initial_stats) + {played, wins, draws, lost, points} = Map.get(results, team, @initial_stats) - Map.put(results, team, { played + 1, wins + 1, draws, lost, points + 3 }) + Map.put(results, team, {played + 1, wins + 1, draws, lost, points + 3}) end defp mark_draw(results, team) do - { played, wins, draws, lost, points } = Map.get(results, team, @initial_stats) + {played, wins, draws, lost, points} = Map.get(results, team, @initial_stats) - Map.put(results, team, { played + 1, wins, draws + 1, lost, points + 1}) + Map.put(results, team, {played + 1, wins, draws + 1, lost, points + 1}) end defp mark_loss(results, team) do - { played, wins, draws, lost, points } = Map.get(results, team, @initial_stats) + {played, wins, draws, lost, points} = Map.get(results, team, @initial_stats) - Map.put(results, team, { played + 1, wins, draws, lost + 1, points}) + Map.put(results, team, {played + 1, wins, draws, lost + 1, points}) end - defp sort_results({_, _, _, _, _, points_a}, {_, _, _, _, _, points_b}) when points_a > points_b, do: true - defp sort_results({_, _, _, _, _, points_a}, {_, _, _, _, _, points_b}) when points_a < points_b, do: false - defp sort_results({name_a, _, _, _, _, _}, {name_b, _, _, _, _, _}) when name_a <= name_b, do: true + defp sort_results({_, _, _, _, _, points_a}, {_, _, _, _, _, points_b}) when points_a > points_b, + do: true + + defp sort_results({_, _, _, _, _, points_a}, {_, _, _, _, _, points_b}) when points_a < points_b, + do: false + + defp sort_results({name_a, _, _, _, _, _}, {name_b, _, _, _, _, _}) when name_a <= name_b, + do: true + defp sort_results(_, _), do: false defp format_results({name, played, wins, draws, lost, points}) do @@ -75,7 +82,7 @@ defmodule Tournament do draws |> to_string |> String.pad_leading(2), lost |> to_string |> String.pad_leading(2), points |> to_string |> String.pad_leading(2) - ] |> Enum.join(" | ") + ] + |> Enum.join(" | ") end end - diff --git a/exercises/tournament/tournament.exs b/exercises/tournament/tournament.exs index 8dcaa121b4..bb7e5b1a81 100644 --- a/exercises/tournament/tournament.exs +++ b/exercises/tournament/tournament.exs @@ -14,4 +14,3 @@ defmodule Tournament do def tally(input) do end end - diff --git a/exercises/tournament/tournament_test.exs b/exercises/tournament/tournament_test.exs index 3ca0d3aa07..7b7998ec46 100644 --- a/exercises/tournament/tournament_test.exs +++ b/exercises/tournament/tournament_test.exs @@ -2,13 +2,13 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("tournament.exs", __DIR__) end -ExUnit.start -ExUnit.configure trace: true, exclude: :pending +ExUnit.start() +ExUnit.configure(trace: true, exclude: :pending) defmodule TournamentTest do use ExUnit.Case - #@tag :pending + # @tag :pending test "typical input" do input = [ "Allegoric Alaskans;Blithering Badgers;win", @@ -19,13 +19,15 @@ defmodule TournamentTest do "Allegoric Alaskans;Courageous Californians;win" ] - expected = """ - Team | MP | W | D | L | P - Devastating Donkeys | 3 | 2 | 1 | 0 | 7 - Allegoric Alaskans | 3 | 2 | 0 | 1 | 6 - Blithering Badgers | 3 | 1 | 0 | 2 | 3 - Courageous Californians | 3 | 0 | 1 | 2 | 1 - """ |> String.trim + expected = + """ + Team | MP | W | D | L | P + Devastating Donkeys | 3 | 2 | 1 | 0 | 7 + Allegoric Alaskans | 3 | 2 | 0 | 1 | 6 + Blithering Badgers | 3 | 1 | 0 | 2 | 3 + Courageous Californians | 3 | 0 | 1 | 2 | 1 + """ + |> String.trim() assert Tournament.tally(input) == expected end @@ -39,13 +41,15 @@ defmodule TournamentTest do "Allegoric Alaskans;Courageous Californians;win" ] - expected = """ - Team | MP | W | D | L | P - Allegoric Alaskans | 3 | 2 | 0 | 1 | 6 - Blithering Badgers | 2 | 1 | 1 | 0 | 4 - Courageous Californians | 2 | 0 | 1 | 1 | 1 - Devastating Donkeys | 1 | 0 | 0 | 1 | 0 - """ |> String.trim + expected = + """ + Team | MP | W | D | L | P + Allegoric Alaskans | 3 | 2 | 0 | 1 | 6 + Blithering Badgers | 2 | 1 | 1 | 0 | 4 + Courageous Californians | 2 | 0 | 1 | 1 | 1 + Devastating Donkeys | 1 | 0 | 0 | 1 | 0 + """ + |> String.trim() assert Tournament.tally(input) == expected end @@ -61,13 +65,15 @@ defmodule TournamentTest do "Allegoric Alaskans;Courageous Californians;draw" ] - expected = """ - Team | MP | W | D | L | P - Allegoric Alaskans | 3 | 2 | 1 | 0 | 7 - Courageous Californians | 3 | 2 | 1 | 0 | 7 - Blithering Badgers | 3 | 0 | 1 | 2 | 1 - Devastating Donkeys | 3 | 0 | 1 | 2 | 1 - """ |> String.trim + expected = + """ + Team | MP | W | D | L | P + Allegoric Alaskans | 3 | 2 | 1 | 0 | 7 + Courageous Californians | 3 | 2 | 1 | 0 | 7 + Blithering Badgers | 3 | 0 | 1 | 2 | 1 + Devastating Donkeys | 3 | 0 | 1 | 2 | 1 + """ + |> String.trim() assert Tournament.tally(input) == expected end @@ -84,13 +90,14 @@ defmodule TournamentTest do "Courageous Californians;Allegoric Alaskans;los" ] - expected = """ - Team | MP | W | D | L | P - Devastating Donkeys | 1 | 1 | 0 | 0 | 3 - Blithering Badgers | 1 | 0 | 0 | 1 | 0 - """ |> String.trim + expected = + """ + Team | MP | W | D | L | P + Devastating Donkeys | 1 | 1 | 0 | 0 | 3 + Blithering Badgers | 1 | 0 | 0 | 1 | 0 + """ + |> String.trim() assert Tournament.tally(input) == expected end end - diff --git a/exercises/transpose/example.exs b/exercises/transpose/example.exs index 1818249618..8f7bf3ce14 100644 --- a/exercises/transpose/example.exs +++ b/exercises/transpose/example.exs @@ -16,7 +16,7 @@ defmodule Transpose do "AD\nBE\n F" """ - @spec transpose(String.t) :: String.t + @spec transpose(String.t()) :: String.t() def transpose(matrix) do rows = String.split(matrix, "\n") @@ -25,18 +25,18 @@ defmodule Transpose do rows |> Enum.map(fn x -> get_padded_row(x, max_length) end) |> Enum.map(fn x -> String.to_charlist(x) end) - |> List.zip + |> List.zip() |> Enum.map(fn x -> Tuple.to_list(x) end) |> Enum.map(fn x -> List.to_string(x) end) |> Enum.map(fn x -> String.replace(x, "*", " ") end) |> Enum.join("\n") - |> String.trim_trailing + |> String.trim_trailing() end defp get_longest_row_length(rows) do rows |> Enum.map(fn row -> String.length(row) end) - |> Enum.max + |> Enum.max() end defp get_padded_row(row, max_length) do diff --git a/exercises/transpose/transpose.exs b/exercises/transpose/transpose.exs index c51ef1bae0..39eab4b73f 100644 --- a/exercises/transpose/transpose.exs +++ b/exercises/transpose/transpose.exs @@ -16,7 +16,7 @@ defmodule Transpose do "AD\nBE\n F" """ - @spec transpose(String.t) :: String.t + @spec transpose(String.t()) :: String.t() def transpose(input) do end end diff --git a/exercises/transpose/transpose_test.exs b/exercises/transpose/transpose_test.exs index c1e77391c2..a7d4f9fbb0 100644 --- a/exercises/transpose/transpose_test.exs +++ b/exercises/transpose/transpose_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("transpose.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule TransposeTest do use ExUnit.Case @@ -17,19 +17,15 @@ defmodule TransposeTest do @tag :pending test "two characters in a row" do - input= "AB" - expected = - "A\n" <> - "B" + input = "AB" + expected = "A\n" <> "B" assert Transpose.transpose(input) == expected end @tag :pending test "two characters in one column" do - input= - "A\n" <> - "B" + input = "A\n" <> "B" expected = "AB" @@ -42,130 +38,70 @@ defmodule TransposeTest do expected = "S\n" <> - "i\n" <> - "n\n" <> - "g\n" <> - "l\n" <> - "e\n" <> - " \n" <> - "l\n" <> - "i\n" <> - "n\n" <> - "e\n" <> - "." - - assert Transpose.transpose(input) == expected + "i\n" <> + "n\n" <> "g\n" <> "l\n" <> "e\n" <> " \n" <> "l\n" <> "i\n" <> "n\n" <> "e\n" <> "." + + assert Transpose.transpose(input) == expected end @tag :pending test "first line longer than second line" do - input = "The fourth line.\n" <> - "The fifth line." + input = "The fourth line.\n" <> "The fifth line." - expected = - "TT\n" <> + expected = + "TT\n" <> "hh\n" <> "ee\n" <> " \n" <> "ff\n" <> "oi\n" <> "uf\n" <> - "rt\n" <> - "th\n" <> - "h \n" <> - " l\n" <> - "li\n" <> - "in\n" <> - "ne\n" <> - "e.\n" <> - "." - - assert Transpose.transpose(input) == expected + "rt\n" <> "th\n" <> "h \n" <> " l\n" <> "li\n" <> "in\n" <> "ne\n" <> "e.\n" <> "." + + assert Transpose.transpose(input) == expected end @tag :pending test "second line longer than first line" do - input = "The first line.\n" <> - "The second line." + input = "The first line.\n" <> "The second line." - expected = - "TT\n" <> + expected = + "TT\n" <> "hh\n" <> "ee\n" <> " \n" <> "fs\n" <> "ie\n" <> "rc\n" <> - "so\n" <> - "tn\n" <> - " d\n" <> - "l \n" <> - "il\n" <> - "ni\n" <> - "en\n" <> - ".e\n" <> - " ." - - assert Transpose.transpose(input) == expected + "so\n" <> "tn\n" <> " d\n" <> "l \n" <> "il\n" <> "ni\n" <> "en\n" <> ".e\n" <> " ." + + assert Transpose.transpose(input) == expected end @tag :pending test "square" do - matrix = - "HEART\n" <> - "EMBER\n" <> - "ABUSE\n" <> - "RESIN\n" <> - "TREND" + matrix = "HEART\n" <> "EMBER\n" <> "ABUSE\n" <> "RESIN\n" <> "TREND" - expected = - "HEART\n" <> - "EMBER\n" <> - "ABUSE\n" <> - "RESIN\n" <> - "TREND" + expected = "HEART\n" <> "EMBER\n" <> "ABUSE\n" <> "RESIN\n" <> "TREND" assert Transpose.transpose(matrix) == expected end @tag :pending test "rectangle" do - matrix = - "FRACTURE\n" <> - "OUTLINED\n" <> - "BLOOMING\n" <> - "SEPTETTE" + matrix = "FRACTURE\n" <> "OUTLINED\n" <> "BLOOMING\n" <> "SEPTETTE" expected = - "FOBS\n" <> - "RULE\n" <> - "ATOP\n" <> - "CLOT\n" <> - "TIME\n" <> - "UNIT\n" <> - "RENT\n" <> - "EDGE" + "FOBS\n" <> "RULE\n" <> "ATOP\n" <> "CLOT\n" <> "TIME\n" <> "UNIT\n" <> "RENT\n" <> "EDGE" assert Transpose.transpose(matrix) == expected end @tag :pending test "triangle" do - matrix = - "T\n" <> - "EE\n" <> - "AAA\n" <> - "SSSS\n" <> - "EEEEE\n" <> - "RRRRRR" + matrix = "T\n" <> "EE\n" <> "AAA\n" <> "SSSS\n" <> "EEEEE\n" <> "RRRRRR" - expected = - "TEASER\n" <> - " EASER\n" <> - " ASER\n" <> - " SER\n" <> - " ER\n" <> - " R" + expected = "TEASER\n" <> " EASER\n" <> " ASER\n" <> " SER\n" <> " ER\n" <> " R" assert Transpose.transpose(matrix) == expected end @@ -174,74 +110,71 @@ defmodule TransposeTest do test "many lines" do matrix = "Chor. Two households, both alike in dignity,\n" <> - "In fair Verona, where we lay our scene,\n" <> - "From ancient grudge break to new mutiny,\n" <> - "Where civil blood makes civil hands unclean.\n" <> - "From forth the fatal loins of these two foes\n" <> - "A pair of star-cross'd lovers take their life;\n" <> - "Whose misadventur'd piteous overthrows\n" <> - "Doth with their death bury their parents' strife.\n" <> - "The fearful passage of their death-mark'd love,\n" <> - "And the continuance of their parents' rage,\n" <> - "Which, but their children's end, naught could remove,\n" <> - "Is now the two hours' traffic of our stage;\n" <> - "The which if you with patient ears attend,\n" <> - "What here shall miss, our toil shall strive to mend." + "In fair Verona, where we lay our scene,\n" <> + "From ancient grudge break to new mutiny,\n" <> + "Where civil blood makes civil hands unclean.\n" <> + "From forth the fatal loins of these two foes\n" <> + "A pair of star-cross'd lovers take their life;\n" <> + "Whose misadventur'd piteous overthrows\n" <> + "Doth with their death bury their parents' strife.\n" <> + "The fearful passage of their death-mark'd love,\n" <> + "And the continuance of their parents' rage,\n" <> + "Which, but their children's end, naught could remove,\n" <> + "Is now the two hours' traffic of our stage;\n" <> + "The which if you with patient ears attend,\n" <> + "What here shall miss, our toil shall strive to mend." expected = "CIFWFAWDTAWITW\n" <> - "hnrhr hohnhshh\n" <> - "o oeopotedi ea\n" <> - "rfmrmash cn t\n" <> - ".a e ie fthow \n" <> - " ia fr weh,whh\n" <> - "Trnco miae ie\n" <> - "w ciroitr btcr\n" <> - "oVivtfshfcuhhe\n" <> - " eeih a uote \n" <> - "hrnl sdtln is\n" <> - "oot ttvh tttfh\n" <> - "un bhaeepihw a\n" <> - "saglernianeoyl\n" <> - "e,ro -trsui ol\n" <> - "h uofcu sarhu \n" <> - "owddarrdan o m\n" <> - "lhg to'egccuwi\n" <> - "deemasdaeehris\n" <> - "sr als t ists\n" <> - ",ebk 'phool'h,\n" <> - " reldi ffd \n" <> - "bweso tb rtpo\n" <> - "oea ileutterau\n" <> - "t kcnoorhhnatr\n" <> - "hl isvuyee'fi \n" <> - " atv es iisfet\n" <> - "ayoior trr ino\n" <> - "l lfsoh ecti\n" <> - "ion vedpn l\n" <> - "kuehtteieadoe \n" <> - "erwaharrar,fas\n" <> - " nekt te rh\n" <> - "ismdsehphnnosa\n" <> - "ncuse ra-tau l\n" <> - " et tormsural\n" <> - "dniuthwea'g t \n" <> - "iennwesnr hsts\n" <> - "g,ycoi tkrttet\n" <> - "n ,l r s'a anr\n" <> - "i ef 'dgcgdi\n" <> - "t aol eoe,v\n" <> - "y nei sl,u; e\n" <> - ", .sf to l \n" <> - " e rv d t\n" <> - " ; ie o\n" <> - " f, r \n" <> - " e e m\n" <> - " . m e\n" <> - " o n\n" <> - " v d\n" <> - " e .\n" <> - " ," + "hnrhr hohnhshh\n" <> + "o oeopotedi ea\n" <> + "rfmrmash cn t\n" <> + ".a e ie fthow \n" <> + " ia fr weh,whh\n" <> + "Trnco miae ie\n" <> + "w ciroitr btcr\n" <> + "oVivtfshfcuhhe\n" <> + " eeih a uote \n" <> + "hrnl sdtln is\n" <> + "oot ttvh tttfh\n" <> + "un bhaeepihw a\n" <> + "saglernianeoyl\n" <> + "e,ro -trsui ol\n" <> + "h uofcu sarhu \n" <> + "owddarrdan o m\n" <> + "lhg to'egccuwi\n" <> + "deemasdaeehris\n" <> + "sr als t ists\n" <> + ",ebk 'phool'h,\n" <> + " reldi ffd \n" <> + "bweso tb rtpo\n" <> + "oea ileutterau\n" <> + "t kcnoorhhnatr\n" <> + "hl isvuyee'fi \n" <> + " atv es iisfet\n" <> + "ayoior trr ino\n" <> + "l lfsoh ecti\n" <> + "ion vedpn l\n" <> + "kuehtteieadoe \n" <> + "erwaharrar,fas\n" <> + " nekt te rh\n" <> + "ismdsehphnnosa\n" <> + "ncuse ra-tau l\n" <> + " et tormsural\n" <> + "dniuthwea'g t \n" <> + "iennwesnr hsts\n" <> + "g,ycoi tkrttet\n" <> + "n ,l r s'a anr\n" <> + "i ef 'dgcgdi\n" <> + "t aol eoe,v\n" <> + "y nei sl,u; e\n" <> + ", .sf to l \n" <> + " e rv d t\n" <> + " ; ie o\n" <> + " f, r \n" <> + " e e m\n" <> + " . m e\n" <> + " o n\n" <> " v d\n" <> " e .\n" <> " ," assert Transpose.transpose(matrix) == expected end diff --git a/exercises/triangle/example.exs b/exercises/triangle/example.exs index 38074238d0..7790ff7611 100644 --- a/exercises/triangle/example.exs +++ b/exercises/triangle/example.exs @@ -1,10 +1,10 @@ defmodule Triangle do - def kind(a, b, c), do: kind Enum.sort [a, b, c] + def kind(a, b, c), do: kind(Enum.sort([a, b, c])) - defp kind([a, _, _]) when a <= 0, do: { :error, "all side lengths must be positive" } - defp kind([a, b, c]) when a + b <= c, do: { :error, "side lengths violate triangle inequality" } - defp kind([x, x, x]), do: { :ok, :equilateral } - defp kind([x, x, _]), do: { :ok, :isosceles } - defp kind([_, x, x]), do: { :ok, :isosceles } - defp kind([_, _, _]), do: { :ok, :scalene } + defp kind([a, _, _]) when a <= 0, do: {:error, "all side lengths must be positive"} + defp kind([a, b, c]) when a + b <= c, do: {:error, "side lengths violate triangle inequality"} + defp kind([x, x, x]), do: {:ok, :equilateral} + defp kind([x, x, _]), do: {:ok, :isosceles} + defp kind([_, x, x]), do: {:ok, :isosceles} + defp kind([_, _, _]), do: {:ok, :scalene} end diff --git a/exercises/triangle/triangle.exs b/exercises/triangle/triangle.exs index 3f9faf4763..f5786a8fbc 100644 --- a/exercises/triangle/triangle.exs +++ b/exercises/triangle/triangle.exs @@ -4,8 +4,7 @@ defmodule Triangle do @doc """ Return the kind of triangle of a triangle with 'a', 'b' and 'c' as lengths. """ - @spec kind(number, number, number) :: { :ok, kind } | { :error, String.t } + @spec kind(number, number, number) :: {:ok, kind} | {:error, String.t()} def kind(a, b, c) do - end end diff --git a/exercises/triangle/triangle_test.exs b/exercises/triangle/triangle_test.exs index 115c9a64fd..31ed7f1ec4 100644 --- a/exercises/triangle/triangle_test.exs +++ b/exercises/triangle/triangle_test.exs @@ -2,84 +2,84 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("triangle.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule TriangleTest do use ExUnit.Case # @tag :pending test "equilateral triangles have equal sides" do - assert Triangle.kind(2, 2, 2) == { :ok, :equilateral } + assert Triangle.kind(2, 2, 2) == {:ok, :equilateral} end @tag :pending test "larger equilateral triangles also have equal sides" do - assert Triangle.kind(10, 10, 10) == { :ok, :equilateral } + assert Triangle.kind(10, 10, 10) == {:ok, :equilateral} end @tag :pending test "isosceles triangles have last two sides equal" do - assert Triangle.kind(3, 4, 4) == { :ok, :isosceles } + assert Triangle.kind(3, 4, 4) == {:ok, :isosceles} end @tag :pending test "isosceles triangles have first and last sides equal" do - assert Triangle.kind(4, 3, 4) == { :ok, :isosceles } + assert Triangle.kind(4, 3, 4) == {:ok, :isosceles} end @tag :pending test "isosceles triangles have two first sides equal" do - assert Triangle.kind(4, 4, 3) == { :ok, :isosceles } + assert Triangle.kind(4, 4, 3) == {:ok, :isosceles} end @tag :pending test "isosceles triangles have in fact exactly two sides equal" do - assert Triangle.kind(10, 10, 2) == { :ok, :isosceles } + assert Triangle.kind(10, 10, 2) == {:ok, :isosceles} end @tag :pending test "scalene triangles have no equal sides" do - assert Triangle.kind(3, 4, 5) == { :ok, :scalene } + assert Triangle.kind(3, 4, 5) == {:ok, :scalene} end @tag :pending test "scalene triangles have no equal sides at a larger scale too" do - assert Triangle.kind(10, 11, 12) == { :ok, :scalene } + assert Triangle.kind(10, 11, 12) == {:ok, :scalene} end @tag :pending test "scalene triangles have no equal sides in descending order either" do - assert Triangle.kind(5, 4, 2) == { :ok, :scalene } + assert Triangle.kind(5, 4, 2) == {:ok, :scalene} end @tag :pending test "very small triangles are legal" do - assert Triangle.kind(0.4, 0.6, 0.3) == { :ok, :scalene } + assert Triangle.kind(0.4, 0.6, 0.3) == {:ok, :scalene} end @tag :pending test "triangles with no size are illegal" do - assert Triangle.kind(0, 0, 0) == { :error, "all side lengths must be positive" } + assert Triangle.kind(0, 0, 0) == {:error, "all side lengths must be positive"} end @tag :pending test "triangles with negative sides are illegal" do - assert Triangle.kind(3, 4, -5) == { :error, "all side lengths must be positive" } + assert Triangle.kind(3, 4, -5) == {:error, "all side lengths must be positive"} end @tag :pending test "triangles violating triangle inequality are illegal" do - assert Triangle.kind(1, 1, 3) == { :error, "side lengths violate triangle inequality" } + assert Triangle.kind(1, 1, 3) == {:error, "side lengths violate triangle inequality"} end @tag :pending test "triangles violating triangle inequality are illegal 2" do - assert Triangle.kind(2, 4, 2) == { :error, "side lengths violate triangle inequality" } + assert Triangle.kind(2, 4, 2) == {:error, "side lengths violate triangle inequality"} end @tag :pending test "triangles violating triangle inequality are illegal 3" do - assert Triangle.kind(7, 3, 2) == { :error, "side lengths violate triangle inequality" } + assert Triangle.kind(7, 3, 2) == {:error, "side lengths violate triangle inequality"} end end diff --git a/exercises/twelve-days/example.exs b/exercises/twelve-days/example.exs index 47fa0e3c45..046f53fef1 100644 --- a/exercises/twelve-days/example.exs +++ b/exercises/twelve-days/example.exs @@ -14,10 +14,10 @@ defmodule TwelveDays do {"twelve", "twelfth", "Drummers Drumming"} ] - for { { count, ordinal, gift }, number } <- @days |> Enum.with_index(1) do + for {{count, ordinal, gift}, number} <- @days |> Enum.with_index(1) do defp count(unquote(number)), do: unquote(count) defp ordinal(unquote(number)), do: unquote(ordinal) - defp gift(unquote(number)), do: "#{count(unquote(number))} #{ unquote(gift) }" + defp gift(unquote(number)), do: "#{count(unquote(number))} #{unquote(gift)}" end @doc """ @@ -26,11 +26,16 @@ defmodule TwelveDays do """ @spec verse(number :: integer) :: String.t() def verse(number) do - "On the #{ordinal(number)} day of Christmas my true love gave to me, #{gifts_for_day(number, [])}." + "On the #{ordinal(number)} day of Christmas my true love gave to me, #{ + gifts_for_day(number, []) + }." end defp gifts_for_day(1, []), do: gift(1) - defp gifts_for_day(1, results), do: ["and #{gift(1)}" | results] |> Enum.reverse |> Enum.join(", ") + + defp gifts_for_day(1, results), + do: ["and #{gift(1)}" | results] |> Enum.reverse() |> Enum.join(", ") + defp gifts_for_day(number, results), do: gifts_for_day(number - 1, [gift(number) | results]) @doc """ @@ -47,7 +52,6 @@ defmodule TwelveDays do @doc """ Sing all 12 verses, in order, one verse per line. """ - @spec sing():: String.t() + @spec sing() :: String.t() def sing, do: verses(1, 12) end - diff --git a/exercises/twelve-days/twelve_days.exs b/exercises/twelve-days/twelve_days.exs index b731b71fd2..e67f42b981 100644 --- a/exercises/twelve-days/twelve_days.exs +++ b/exercises/twelve-days/twelve_days.exs @@ -18,8 +18,7 @@ defmodule TwelveDays do @doc """ Sing all 12 verses, in order, one verse per line. """ - @spec sing():: String.t() + @spec sing() :: String.t() def sing do end end - diff --git a/exercises/twelve-days/twelve_days_test.exs b/exercises/twelve-days/twelve_days_test.exs index 58eb42b316..143121da89 100644 --- a/exercises/twelve-days/twelve_days_test.exs +++ b/exercises/twelve-days/twelve_days_test.exs @@ -2,85 +2,95 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("twelve_days.exs", __DIR__) end -ExUnit.start -ExUnit.configure trace: true, exclude: :pending +ExUnit.start() +ExUnit.configure(trace: true, exclude: :pending) defmodule TwelveDaysTest do use ExUnit.Case describe "verse" do - #@tag :pending + # @tag :pending test "first verse" do - assert TwelveDays.verse(1) == "On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree." + assert TwelveDays.verse(1) == + "On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree." end @tag :pending test "sixth verse" do - assert TwelveDays.verse(6) == "On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree." + assert TwelveDays.verse(6) == + "On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree." end @tag :pending test "last verse" do - assert TwelveDays.verse(12) == "On the twelfth day of Christmas my true love gave to me, twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree." + assert TwelveDays.verse(12) == + "On the twelfth day of Christmas my true love gave to me, twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree." end end describe "verses" do @tag :pending test "1-3" do - assert TwelveDays.verses(1, 3) == """ - On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree. - On the second day of Christmas my true love gave to me, two Turtle Doves, and a Partridge in a Pear Tree. - On the third day of Christmas my true love gave to me, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - """ |> String.trim + assert TwelveDays.verses(1, 3) == + """ + On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree. + On the second day of Christmas my true love gave to me, two Turtle Doves, and a Partridge in a Pear Tree. + On the third day of Christmas my true love gave to me, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + """ + |> String.trim() end @tag :pending test "4-6" do - assert TwelveDays.verses(4, 6) == """ - On the fourth day of Christmas my true love gave to me, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the fifth day of Christmas my true love gave to me, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - """ |> String.trim + assert TwelveDays.verses(4, 6) == + """ + On the fourth day of Christmas my true love gave to me, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the fifth day of Christmas my true love gave to me, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + """ + |> String.trim() end @tag :pending test "1-12" do - assert TwelveDays.verses(1, 12) == """ - On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree. - On the second day of Christmas my true love gave to me, two Turtle Doves, and a Partridge in a Pear Tree. - On the third day of Christmas my true love gave to me, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the fourth day of Christmas my true love gave to me, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the fifth day of Christmas my true love gave to me, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the seventh day of Christmas my true love gave to me, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the eighth day of Christmas my true love gave to me, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the ninth day of Christmas my true love gave to me, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the tenth day of Christmas my true love gave to me, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the eleventh day of Christmas my true love gave to me, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the twelfth day of Christmas my true love gave to me, twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - """ |> String.trim + assert TwelveDays.verses(1, 12) == + """ + On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree. + On the second day of Christmas my true love gave to me, two Turtle Doves, and a Partridge in a Pear Tree. + On the third day of Christmas my true love gave to me, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the fourth day of Christmas my true love gave to me, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the fifth day of Christmas my true love gave to me, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the seventh day of Christmas my true love gave to me, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the eighth day of Christmas my true love gave to me, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the ninth day of Christmas my true love gave to me, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the tenth day of Christmas my true love gave to me, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the eleventh day of Christmas my true love gave to me, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the twelfth day of Christmas my true love gave to me, twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + """ + |> String.trim() end end describe "sing" do @tag :pending test "all 12 verses" do - assert TwelveDays.sing == """ - On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree. - On the second day of Christmas my true love gave to me, two Turtle Doves, and a Partridge in a Pear Tree. - On the third day of Christmas my true love gave to me, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the fourth day of Christmas my true love gave to me, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the fifth day of Christmas my true love gave to me, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the seventh day of Christmas my true love gave to me, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the eighth day of Christmas my true love gave to me, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the ninth day of Christmas my true love gave to me, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the tenth day of Christmas my true love gave to me, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the eleventh day of Christmas my true love gave to me, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - On the twelfth day of Christmas my true love gave to me, twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. - """ |> String.trim + assert TwelveDays.sing() == + """ + On the first day of Christmas my true love gave to me, a Partridge in a Pear Tree. + On the second day of Christmas my true love gave to me, two Turtle Doves, and a Partridge in a Pear Tree. + On the third day of Christmas my true love gave to me, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the fourth day of Christmas my true love gave to me, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the fifth day of Christmas my true love gave to me, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the sixth day of Christmas my true love gave to me, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the seventh day of Christmas my true love gave to me, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the eighth day of Christmas my true love gave to me, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the ninth day of Christmas my true love gave to me, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the tenth day of Christmas my true love gave to me, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the eleventh day of Christmas my true love gave to me, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + On the twelfth day of Christmas my true love gave to me, twelve Drummers Drumming, eleven Pipers Piping, ten Lords-a-Leaping, nine Ladies Dancing, eight Maids-a-Milking, seven Swans-a-Swimming, six Geese-a-Laying, five Gold Rings, four Calling Birds, three French Hens, two Turtle Doves, and a Partridge in a Pear Tree. + """ + |> String.trim() end end end - diff --git a/exercises/word-count/example.exs b/exercises/word-count/example.exs index 3853e8c3e1..b2a29b3c7e 100644 --- a/exercises/word-count/example.exs +++ b/exercises/word-count/example.exs @@ -3,15 +3,15 @@ defmodule Words do def count(sentence) do sentence - |> String.downcase - |> remove_punctuation - |> to_words - |> summarize + |> String.downcase() + |> remove_punctuation + |> to_words + |> summarize end defp remove_punctuation(string), do: String.replace(string, @ascii_punctuation, " ") - defp to_words(sentence), do: List.flatten String.split(sentence) + defp to_words(sentence), do: List.flatten(String.split(sentence)) defp summarize(words) do Enum.reduce(words, %{}, &add_count/2) diff --git a/exercises/word-count/word_count.exs b/exercises/word-count/word_count.exs index 62b0bc570e..6b65fc218e 100644 --- a/exercises/word-count/word_count.exs +++ b/exercises/word-count/word_count.exs @@ -4,8 +4,7 @@ defmodule Words do Words are compared case-insensitively. """ - @spec count(String.t) :: map + @spec count(String.t()) :: map def count(sentence) do - end end diff --git a/exercises/word-count/word_count_test.exs b/exercises/word-count/word_count_test.exs index 9b127a2a6d..6ad9e59def 100644 --- a/exercises/word-count/word_count_test.exs +++ b/exercises/word-count/word_count_test.exs @@ -2,25 +2,25 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("word_count.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule WordsTest do use ExUnit.Case test "count one word" do - assert Words.count("word") == %{ "word" => 1 } + assert Words.count("word") == %{"word" => 1} end @tag :pending test "count one of each" do - expected = %{ "one" => 1 , "of" => 1 , "each" => 1 } + expected = %{"one" => 1, "of" => 1, "each" => 1} assert Words.count("one of each") == expected end @tag :pending test "count multiple occurrences" do - expected = %{ "one" => 1 , "fish" => 4 , "two" => 1 , "red" => 1 , "blue" => 1 } + expected = %{"one" => 1, "fish" => 4, "two" => 1, "red" => 1, "blue" => 1} assert Words.count("one fish two fish red fish blue fish") == expected end diff --git a/exercises/wordy/example.exs b/exercises/wordy/example.exs index 5dc7f8b87d..4b9f141a65 100644 --- a/exercises/wordy/example.exs +++ b/exercises/wordy/example.exs @@ -6,7 +6,7 @@ defmodule Wordy do @doc """ Calculate the math problem in the sentence. """ - @spec answer(String.t) :: integer + @spec answer(String.t()) :: integer def answer(question) do question |> tokenize @@ -17,34 +17,33 @@ defmodule Wordy do defp tokenize(sentence) do Regex.scan(~r/(#{all_matchers()})/, sentence) - |> Enum.map(&(Enum.at(&1,0))) + |> Enum.map(&Enum.at(&1, 0)) end defp all_matchers do - Enum.map(@parts, &(&1.matcher)) |> Enum.join("|") + Enum.map(@parts, & &1.matcher) |> Enum.join("|") end defp parse(tokens) do - for token <- tokens, - part = Enum.find(@parts, &(&1.match?(token))) do + for token <- tokens, part = Enum.find(@parts, & &1.match?(token)) do part.parse(token) end end defp validate(parsed) do - if Enum.find(parsed, &(is_function &1)) do + if Enum.find(parsed, &is_function(&1)) do parsed else raise ArgumentError end end - defp calculate([ left | [] ] ) do + defp calculate([left | []]) do left end - defp calculate([ left, operation, right | t ]) do - calculate([ operation.(left, right) | t ]) + defp calculate([left, operation, right | t]) do + calculate([operation.(left, right) | t]) end defmodule Number do @@ -53,7 +52,7 @@ defmodule Wordy do end def match?(token) do - String.match?(token,~r/#{matcher()}/) + String.match?(token, ~r/#{matcher()}/) end def parse(token) do @@ -67,7 +66,7 @@ defmodule Wordy do end def match?(token) do - String.match?(token,~r/#{matcher()}/) + String.match?(token, ~r/#{matcher()}/) end def parse(_) do @@ -85,7 +84,7 @@ defmodule Wordy do end def match?(token) do - String.match?(token,~r/#{matcher()}/) + String.match?(token, ~r/#{matcher()}/) end def parse(_) do @@ -103,7 +102,7 @@ defmodule Wordy do end def match?(token) do - String.match?(token,~r/#{matcher()}/) + String.match?(token, ~r/#{matcher()}/) end def parse(_) do @@ -121,7 +120,7 @@ defmodule Wordy do end def match?(token) do - String.match?(token,~r/#{matcher()}/) + String.match?(token, ~r/#{matcher()}/) end def parse(_) do diff --git a/exercises/wordy/wordy.exs b/exercises/wordy/wordy.exs index ce4b51a6e4..f6a3a03169 100644 --- a/exercises/wordy/wordy.exs +++ b/exercises/wordy/wordy.exs @@ -1,11 +1,8 @@ defmodule Wordy do - @doc """ Calculate the math problem in the sentence. """ - @spec answer(String.t) :: integer + @spec answer(String.t()) :: integer def answer(question) do - end - end diff --git a/exercises/wordy/wordy_test.exs b/exercises/wordy/wordy_test.exs index 61e4b5615a..ff6430a3d1 100644 --- a/exercises/wordy/wordy_test.exs +++ b/exercises/wordy/wordy_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("wordy.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule WordyTest do use ExUnit.Case diff --git a/exercises/zipper/example.exs b/exercises/zipper/example.exs index 23d5dca3e0..e32ff1d586 100644 --- a/exercises/zipper/example.exs +++ b/exercises/zipper/example.exs @@ -1,5 +1,6 @@ defmodule BinTree do import Inspect.Algebra + @moduledoc """ A node in a binary tree. @@ -7,7 +8,7 @@ defmodule BinTree do `left` is the left subtree (nil if no subtree). `right` is the right subtree (nil if no subtree). """ - @type t :: %BinTree{ value: any, left: BinTree.t | nil, right: BinTree.t | nil } + @type t :: %BinTree{value: any, left: BinTree.t() | nil, right: BinTree.t() | nil} defstruct value: nil, left: nil, right: nil # A custom inspect instance purely for the tests, this makes error messages @@ -15,10 +16,15 @@ defmodule BinTree do # # BT[value: 3, left: BT[value: 5, right: BT[value: 6]]] becomes (3:(5::(6::)):) def inspect(%BinTree{value: v, left: l, right: r}, opts) do - concat ["(", to_doc(v, opts), - ":", (if l, do: to_doc(l, opts), else: ""), - ":", (if r, do: to_doc(r, opts), else: ""), - ")"] + concat([ + "(", + to_doc(v, opts), + ":", + if(l, do: to_doc(l, opts), else: ""), + ":", + if(r, do: to_doc(r, opts), else: ""), + ")" + ]) end end @@ -35,11 +41,11 @@ defmodule BinTree.Zipper do and the alternative branches. """ @type t :: %BinTree.Zipper{ - value: any, - left: BinTree.Zipper.t | nil, - right: BinTree.Zipper.t | nil, - trail: [{ :left, any, BinTree.t } | { :right, any, BinTree.t }] - } + value: any, + left: BinTree.Zipper.t() | nil, + right: BinTree.Zipper.t() | nil, + trail: [{:left, any, BinTree.t()} | {:right, any, BinTree.t()}] + } defstruct value: nil, left: nil, right: nil, trail: [] end @@ -50,15 +56,15 @@ defmodule Zipper do @doc """ Get a zipper focussed on the root node. """ - @spec from_tree(BT.t) :: Z.t - def from_tree(%BT{ value: v, left: l, right: r}) do + @spec from_tree(BT.t()) :: Z.t() + def from_tree(%BT{value: v, left: l, right: r}) do %Z{value: v, left: l, right: r, trail: []} end @doc """ Get the complete tree from a zipper. """ - @spec to_tree(Z.t) :: BT.t + @spec to_tree(Z.t()) :: BT.t() def to_tree(%Z{value: v, left: l, right: r, trail: t}) do do_to_tree(%BT{value: v, left: l, right: r}, t) end @@ -66,68 +72,73 @@ defmodule Zipper do defp do_to_tree(b, []) do b end - defp do_to_tree(b, [{ :left, pv, pr } | pt]) do + + defp do_to_tree(b, [{:left, pv, pr} | pt]) do do_to_tree(%BT{value: pv, left: b, right: pr}, pt) end - defp do_to_tree(b, [{ :right, pv, pl } | pt]) do + + defp do_to_tree(b, [{:right, pv, pl} | pt]) do do_to_tree(%BT{value: pv, left: pl, right: b}, pt) end @doc """ Get the value of the focus node. """ - @spec value(Z.t) :: any - def value(%Z{ value: v }), do: v + @spec value(Z.t()) :: any + def value(%Z{value: v}), do: v @doc """ Get the left child of the focus node, if any. """ - @spec left(Z.t) :: Z.t | nil - def left(%Z{ left: nil }), do: nil - def left(%Z{ value: v, left: %BT{value: lv, left: ll, right: lr}, - right: r, trail: zt}) do - %Z{ value: lv, left: ll, right: lr, trail: [{ :left, v, r } | zt] } + @spec left(Z.t()) :: Z.t() | nil + def left(%Z{left: nil}), do: nil + + def left(%Z{value: v, left: %BT{value: lv, left: ll, right: lr}, right: r, trail: zt}) do + %Z{value: lv, left: ll, right: lr, trail: [{:left, v, r} | zt]} end @doc """ Get the right child of the focus node, if any. """ - @spec right(Z.t) :: Z.t | nil - def right(%Z{ right: nil }), do: nil - def right(%Z{ value: v, left: l, - right: %BT{value: rv, left: rl, right: rr}, trail: zt }) do - %Z{ value: rv, left: rl, right: rr, trail: [{ :right, v, l } | zt] } + @spec right(Z.t()) :: Z.t() | nil + def right(%Z{right: nil}), do: nil + + def right(%Z{value: v, left: l, right: %BT{value: rv, left: rl, right: rr}, trail: zt}) do + %Z{value: rv, left: rl, right: rr, trail: [{:right, v, l} | zt]} end @doc """ Get the parent of the focus node, if any. """ - @spec up(Z.t) :: Z.t - def up(%Z{ value: v, left: l, right: r, trail: t }) do + @spec up(Z.t()) :: Z.t() + def up(%Z{value: v, left: l, right: r, trail: t}) do case t do - [] -> nil - [{ :left, pv, pr } | zt] -> - %Z{ value: pv, left: %BT{value: v, left: l, right: r}, right: pr, trail: zt } - [{ :right, pv, pl } | zt] -> - %Z{ value: pv, left: pl, right: %BT{value: v, left: l, right: r}, trail: zt } + [] -> + nil + + [{:left, pv, pr} | zt] -> + %Z{value: pv, left: %BT{value: v, left: l, right: r}, right: pr, trail: zt} + + [{:right, pv, pl} | zt] -> + %Z{value: pv, left: pl, right: %BT{value: v, left: l, right: r}, trail: zt} end end @doc """ Set the value of the focus node. """ - @spec set_value(Z.t, any) :: Z.t + @spec set_value(Z.t(), any) :: Z.t() def set_value(z, v), do: %{z | value: v} @doc """ Replace the left child tree of the focus node. """ - @spec set_left(Z.t, BT.t) :: Z.t + @spec set_left(Z.t(), BT.t()) :: Z.t() def set_left(z, l), do: %{z | left: l} @doc """ Replace the right child tree of the focus node. """ - @spec set_right(Z.t, BT.t) :: Z.t + @spec set_right(Z.t(), BT.t()) :: Z.t() def set_right(z, r), do: %{z | right: r} end diff --git a/exercises/zipper/zipper.exs b/exercises/zipper/zipper.exs index ea1087e3c3..9c7f9ef7c1 100644 --- a/exercises/zipper/zipper.exs +++ b/exercises/zipper/zipper.exs @@ -1,5 +1,6 @@ defmodule BinTree do import Inspect.Algebra + @moduledoc """ A node in a binary tree. @@ -7,7 +8,7 @@ defmodule BinTree do `left` is the left subtree (nil if no subtree). `right` is the right subtree (nil if no subtree). """ - @type t :: %BinTree{ value: any, left: BinTree.t | nil, right: BinTree.t | nil } + @type t :: %BinTree{value: any, left: BinTree.t() | nil, right: BinTree.t() | nil} defstruct value: nil, left: nil, right: nil # A custom inspect instance purely for the tests, this makes error messages @@ -15,10 +16,15 @@ defmodule BinTree do # # BT[value: 3, left: BT[value: 5, right: BT[value: 6]]] becomes (3:(5::(6::)):) def inspect(%BinTree{value: v, left: l, right: r}, opts) do - concat ["(", to_doc(v, opts), - ":", (if l, do: to_doc(l, opts), else: ""), - ":", (if r, do: to_doc(r, opts), else: ""), - ")"] + concat([ + "(", + to_doc(v, opts), + ":", + if(l, do: to_doc(l, opts), else: ""), + ":", + if(r, do: to_doc(r, opts), else: ""), + ")" + ]) end end @@ -26,63 +32,63 @@ defmodule Zipper do @doc """ Get a zipper focused on the root node. """ - @spec from_tree(BT.t) :: Z.t + @spec from_tree(BT.t()) :: Z.t() def from_tree(bt) do end @doc """ Get the complete tree from a zipper. """ - @spec to_tree(Z.t) :: BT.t + @spec to_tree(Z.t()) :: BT.t() def to_tree(z) do end @doc """ Get the value of the focus node. """ - @spec value(Z.t) :: any + @spec value(Z.t()) :: any def value(z) do end @doc """ Get the left child of the focus node, if any. """ - @spec left(Z.t) :: Z.t | nil + @spec left(Z.t()) :: Z.t() | nil def left(z) do end @doc """ Get the right child of the focus node, if any. """ - @spec right(Z.t) :: Z.t | nil + @spec right(Z.t()) :: Z.t() | nil def right(z) do end @doc """ Get the parent of the focus node, if any. """ - @spec up(Z.t) :: Z.t + @spec up(Z.t()) :: Z.t() def up(z) do end @doc """ Set the value of the focus node. """ - @spec set_value(Z.t, any) :: Z.t + @spec set_value(Z.t(), any) :: Z.t() def set_value(z, v) do end @doc """ Replace the left child tree of the focus node. """ - @spec set_left(Z.t, BT.t) :: Z.t + @spec set_left(Z.t(), BT.t()) :: Z.t() def set_left(z, l) do end @doc """ Replace the right child tree of the focus node. """ - @spec set_right(Z.t, BT.t) :: Z.t + @spec set_right(Z.t(), BT.t()) :: Z.t() def set_right(z, r) do end end diff --git a/exercises/zipper/zipper_test.exs b/exercises/zipper/zipper_test.exs index bf7a7d68b3..0ba28bfc31 100644 --- a/exercises/zipper/zipper_test.exs +++ b/exercises/zipper/zipper_test.exs @@ -2,8 +2,8 @@ if !System.get_env("EXERCISM_TEST_EXAMPLES") do Code.load_file("zipper.exs", __DIR__) end -ExUnit.start -ExUnit.configure exclude: :pending, trace: true +ExUnit.start() +ExUnit.configure(exclude: :pending, trace: true) defmodule ZipperTest do alias BinTree, as: BT @@ -13,71 +13,70 @@ defmodule ZipperTest do defp bt(value, left, right), do: %BT{value: value, left: left, right: right} defp leaf(value), do: %BT{value: value} - defp t1, do: bt(1, bt(2, nil, leaf(3)), leaf(4)) - defp t2, do: bt(1, bt(5, nil, leaf(3)), leaf(4)) + defp t1, do: bt(1, bt(2, nil, leaf(3)), leaf(4)) + defp t2, do: bt(1, bt(5, nil, leaf(3)), leaf(4)) defp t3, do: bt(1, bt(2, leaf(5), leaf(3)), leaf(4)) - defp t4, do: bt(1, leaf(2), leaf(4)) - defp t5, do: bt(1, bt(2, nil, leaf(3)), - bt(6, leaf(7), leaf(8))) - defp t6, do: bt(1, bt(2, nil, leaf(5)), leaf(4)) + defp t4, do: bt(1, leaf(2), leaf(4)) + defp t5, do: bt(1, bt(2, nil, leaf(3)), bt(6, leaf(7), leaf(8))) + defp t6, do: bt(1, bt(2, nil, leaf(5)), leaf(4)) # @tag :pending test "data is retained" do - assert (t1() |> from_tree |> to_tree) == t1() + assert t1() |> from_tree |> to_tree == t1() end @tag :pending test "left, right and value" do - assert (t1() |> from_tree |> left |> right |> value) == 3 + assert t1() |> from_tree |> left |> right |> value == 3 end @tag :pending test "dead end" do - assert (t1() |> from_tree |> left |> left) == nil + assert t1() |> from_tree |> left |> left == nil end @tag :pending test "tree from deep focus" do - assert (t1() |> from_tree |> left |> right |> to_tree) == t1() + assert t1() |> from_tree |> left |> right |> to_tree == t1() end @tag :pending test "traversing up from top" do - assert (t1() |> from_tree |> up) == nil + assert t1() |> from_tree |> up == nil end @tag :pending test "left, right, and up" do - assert (t1() |> from_tree |> left |> up |> right |> up |> left |> right |> value) == 3 + assert t1() |> from_tree |> left |> up |> right |> up |> left |> right |> value == 3 end @tag :pending test "set_value" do - assert (t1() |> from_tree |> left |> set_value(5) |> to_tree) == t2() + assert t1() |> from_tree |> left |> set_value(5) |> to_tree == t2() end @tag :pending test "set_value after traversing up" do - assert (t1() |> from_tree |> left |> right |> up |> set_value(5) |> to_tree) == t2() + assert t1() |> from_tree |> left |> right |> up |> set_value(5) |> to_tree == t2() end @tag :pending test "set_left with leaf" do - assert (t1() |> from_tree |> left |> set_left(leaf(5)) |> to_tree) == t3() + assert t1() |> from_tree |> left |> set_left(leaf(5)) |> to_tree == t3() end @tag :pending test "set_right with nil" do - assert (t1() |> from_tree |> left |> set_right(nil) |> to_tree) == t4() + assert t1() |> from_tree |> left |> set_right(nil) |> to_tree == t4() end @tag :pending test "set_right with subtree" do - assert (t1() |> from_tree |> set_right(bt(6, leaf(7), leaf(8))) |> to_tree) == t5() + assert t1() |> from_tree |> set_right(bt(6, leaf(7), leaf(8))) |> to_tree == t5() end @tag :pending test "set_value on deep focus" do - assert (t1() |> from_tree |> left |> right |> set_value(5) |> to_tree) == t6() + assert t1() |> from_tree |> left |> right |> set_value(5) |> to_tree == t6() end end