Elixir genome

Today a triplet of Elixir problems solved 🙂 They are all “human genome” related this time:

Aside from regular enjoyment while working with Elixir (remember? fun, fun, fun !!!), I’ve learned that you can give the head and tail in argument an assignment / name. Simplifies code definitely, here’s an example:

  def hamming_distance(strand1 = [h1|t1], strand2 = [h2|t2]) do
    if length(strand1) != length(strand2) do
      nil
    else
      hamming_distance(t1, t2) + (if h1 == h2, do: 0, else: 1)
    end
  end

As you can see, in the above function, I needed both a complete list, e.g. strand1, but also it’s head an tail. Of course, I could have used the hd/1 and tl/1 functions, but it looks far cleaner this way, at least for me.

Another cool code style I started using more is the function capturing feature:

  def histogram_with_zip(strand) do
    strand!(strand)
    Enum.zip(@nucleotides, Enum.map(@nucleotides, &(count_wo_check(strand, &1)))) |> Enum.into(%{})
  end

  defp strand!(strand) do
    strand |> Enum.map(&(nucleotide!(&1)))
  end

Basically, it allows you to use a short hand for fn(x) -> do_something(x);. It makes the code more compact and easier to read. Of course, one should not overdo it, but for now I quite like the looks of it.

Advertisements
Tagged , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: