Character List: Recursive pattern matching

Hello,

This is my first forum post.
Having read several books on functional programming, I am currently doing my first steps in practical Elixir coding.

One of my first assignments is a recursive pattern match on a character-list. However, the pattern match does not really work. I do not fully understand why I can’t fill up the array with these new characters after performing the pattern match:

defmodule RnaTranscription do
  @doc """
  Transcribes a character list representing DNA nucleotides to RNA

  ## Examples

  iex> RnaTranscription.to_rna('ACTG')
  'UGAC'
  """
  @spec to_rna([char]) :: [char]
  def to_rna([head|tail]) do
       [translate(head)|to_rna(tail)] 
  end

  def to_rna([]), do: []

  defp translate(acid) when acid == 'C' do 'G' end
  defp translate(acid) when acid == 'G' do 'C' end
  defp translate(acid) when acid == 'A' do 'U' end
  defp translate(acid) when acid == 'T' do 'A' end

 end

head when you pass it to translate will be one of the integers 65, 67, 71, or 84, representing the ASCII character A, C, G, and T. though you are checking for 'A', 'C', 'G' and 'T', which are effectively [65], [67], [71] and [84].

You can either use the integers directly or use the ? to have a nicer syntax, eg. ?A.

2 Likes

Great, many thanks! I already figured it out.
I remembered from my book-knowledge that character-lists are represented by integer series but I had no idea with the single character-comparison would fail. In fact, I tried to overcome the issue by wrapping another array ['A'] around the characters.