boddhisattva

boddhisattva

Pattern Matching question related to sum of pairs from Dave Thomas' Elixir for Programmers course

Greetings for the day! Of late, I’ve been doing the Elixir for Programmers course by Dave Thomas and
one of the sections of the course is about Pattern Matching and there’s a particular subsection of that course called “Lists and Recursion” that exposes one to different ways they could use pattern matching in the context of lists.

One of the pattern matching exercises is given a list calculate the sum_pairs. So let’s say your list is: [ 1, 2, 3, 4, 5, 6 ], Lists.sum_pairs( [ 1, 2, 3, 4, 5, 6 ]) should give you: [3, 7, 11]

There’s a particular part of this section which is mostly like a Do it yourself type thing and one of the questions as part of that is: What happens if you give sum_pairs a list with an odd length?.

My approach to solving that was by introducing another function below which basically returns false if the length of a list is odd because sum_pairs is ideally meant to calculate the length of a list with even length and what sum_pairs function does is that it takes a list and returns a list which is half the length of the original list. Additionally, each element in the resultant list is the sum of two elements from the input list.

def sum_pairs([h | t]) when length([h | t]) |> Integer.is_odd == true, do: false

The overall solution looks like:

  @doc """
  Add the ability to calculate the sum of pairs of elements in a list
  ## Examples
    iex> Lists.sum_pairs([])
    []
    iex> Lists.sum_pairs([5, 3, 8, 9])
    [8, 17]
    iex> Lists.sum_pairs([5, 3, 8])
    false
  """
  def sum_pairs([]), do: []
  def sum_pairs([h | t]) when length([h | t]) |> Integer.is_odd == true, do: false
  def sum_pairs([h1, h2 | t]), do: [h1 + h2 | sum_pairs(t)]

I’m curious to learn how you’d go about solving this irrespective of whether you’ve done the course or not. I wanted to look at the course related forum to see if somebody asked a similar question but I didn’t find a search functionality in the course forum to easily search for a related question. @pragdave it would be great to get your take on this as well if feasible. Thank you for the course Dave, really enjoying it so far :slight_smile:

Thank you.

Most Liked

idi527

idi527

I’d iterate over pairs and sum the last element as if with a 0 (nothing) or drop it if there is no pair element for it so that I can avoid calling length. I’d avoid returning false since it makes for a rather unintuitive API.

defmodule Lists do
  @spec sum_pairs([integer]) :: [integer]
  def sum_pairs([]), do: []
  def sum_pairs([_unpaired_element] = t), do: t # [_unpaired_element + 0] or drop it: []
  def sum_pairs([h1, h2 | t]), do: [h1 + h2 | sum_pairs(t)]
end
iex(2)> Lists.sum_pairs([])
[]
iex(3)> Lists.sum_pairs([5, 3, 8, 9])
[8, 17]
iex(4)> Lists.sum_pairs([5, 3, 8])
'\b\b' # [8, 8]

Where Next?

Popular in Chat/Questions Top

Iex.new
Hello!, I just started this week to discover Elixir. I’m a PHP-Programmer and did some sutff in Go too. The more I read about Elixir t...
New
lc0815
hello from a real frustrated newbe… I’m reading this article Full-Stack React With Phoenix (Chapter 3 | Introduction to Phoenix) by mich...
New
shansiddiqui94
Hello all, I recently did my first app in Phoenix and Liveview, many thanks to all the users who assisted me. I found that the tutorial ...
New
wolfiton
Question: Can someone recommend me some good resources on learning performance for phoenix elixir applications and a design pattern I sh...
New
asfand
I already created an Elixir Phoenix app for learning purpose. In this app students of our collage will create profiles, and will chat wit...
New
jslearner
Will learning Erlang really help in being a better Phoenix or Elixir developer or is it a waste of time?
New
pillaiindu
I am a VSCode and Sublime user and I know VIM, though I don't use VIM directly but whenever I code inside Sublime or VSCode, I use Vim em...
New
New
Fl4m3Ph03n1x
Background I am trying to do the typical Ceaser cypher exercise in Elixir. The description of the exercise is as follows: Create an impl...
New
shansiddiqui94
Greetings Elixir Developers, My name is Daniel, and I am taking my first step to learn all about the Elixir language. Currently I have a...
New

Other popular topics Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
dotdotdotPaul
Okay, I'm having a heck of a time trying to figure out how to best handle the validation of belongs_to associations in Ecto. I'm sure I'...
New
AstonJ
You’re a programmer, so you don’t need spoon feeding with the conventional drivel about “this is an integer.” No. You need to know what’s...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 42633 214
New

We're in Beta

About us Mission Statement