nucleotide_count.exs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
defmodule NucleotideCount do
  @nucleotides [?A, ?C, ?G, ?T]

  @doc """
  Counts individual nucleotides in a NucleotideCount strand.

  ## Examples

  iex> NucleotideCount.count('AATAA', ?A)
  4

  iex> NucleotideCount.count('AATAA', ?T)
  1
  """
  @spec count([char], char) :: non_neg_integer
  def count(strand, nucleotide) do
    _count(strand, nucleotide)
  end


  @doc """
  Returns a summary of counts by nucleotide.

  ## Examples

  iex> NucleotideCount.histogram('AATAA')
  %{?A => 4, ?T => 1, ?C => 0, ?G => 0}
  """
  @spec histogram([char]) :: map
  def histogram(strand) do
    strand
    |> _histogram(Map.new(@nucleotides, fn x -> {x, 0} end))
  end

  defp _histogram('', map), do: map
  defp _histogram([head | tail], map) do
    {_, result} = Map.get_and_update(map, head, fn current_value ->
      {current_value, current_value + 1}
    end)
    _histogram(tail, result)
  end

  defp _count('', _nucleotide), do: 0
  defp _count([head | tail], nucleotide) when head == nucleotide do
    1 + _count(tail, nucleotide)
  end
  defp _count([_head | tail], nucleotide) do
    _count(tail, nucleotide)
  end
end

Comments


You're not logged in right now. Please login via GitHub to comment