Pattern Matching a Function Body: Lists

You cannot view this unit as you're not logged in yet. Go to Account to login.

7 Comments

  1. romenigld on December 14, 2020 at 10:58 am

    I like the exercises.
    I just notice the exact number for run the tests.
    They aren’t running in the beginning of each tests.
    Exercise #1: mix test test/lists_test.exs:22
    Exercise #2: mix test test/lists_test.exs:32
    and the so on….

    • Mark Ericksen on March 13, 2021 at 6:43 pm

      Right! You just pick a line that’s inside the test. I like to pick something around the middle so if I add or delete lines, the correct test is still run.

  2. Uzo Enudi on March 13, 2021 at 11:24 am

    Solution:
    def sum_pair([first, second]), do: first + second

    My solution:
    def sum_pair([first, second | []]), do: first + second

    Some overthinking went in there 🙂

    • Mark Ericksen on March 13, 2021 at 6:43 pm

      But hey! It works! 🙂

  3. Maksym Kosenko on December 8, 2021 at 12:25 pm

    For exercise 1 this only one function covers all tests:

    def is_empty?(something), do: something == []
    

    I don’t know if it fits the philosophy of Elixir

    • Mark Ericksen on December 8, 2021 at 12:38 pm

      Ha! Yes, that works. This is more about practicing applying pattern matching in function headers. In case it wasn’t already known, you could use Enum.empty?(something) instead of writing a custom function at all! So, it’s really just about practice. 🙂

  4. Marcus West on August 15, 2024 at 4:31 pm

    def sum_first_2([first, second | tl]), do: [first + second | tl]
    IO.inspect(PatternMatching.Lists.sum_first_2([41,5,119,118]))
    —> ~c”.wv”

    For some reason, it just won’t behave on this. And here is my setup

    pattern_matching/lib/pattern_matching on 🐢 main [!?] ❄️ 🌴🌴 elixir -v
    Erlang/OTP 27 [erts-15.0] [source] [64-bit] [smp:4:4] [ds:4:4:10] [async-threads:1] [jit:ns]

    Elixir 1.17.1 (compiled with Erlang/OTP 27)

Leave a Comment

You must be logged in to post a comment.