Function to return the second letter of each word in Elixir

Yes, just figured it out

1 Like

great.

Do you understand why your original version does not work?
Assuming you just forgot the call to loop.
And expected that var will be set by names().
This is not how a functional language with immutable data works.

def names(phrase) do 
  # this variable is just userless, unused
  var = String.split(phrase)
end

def loop(var) do
  Enum.map(var, fn x ->
    String.at(x, 2)
  end)
end

names()
# there is no variable "var"
loop(var)

what you have to do is rather:

def names(phrase) do 
  String.split(phrase)
end

def loop(var) do
  Enum.map(var, fn x ->
    String.at(x, 2)
  end)
end

var = names()
loop(var)

See the difference?

1 Like

Yes, I figured it out, thanks for explaining further.

I am sure you’re aware of this, but for anyone else who might seek a similar solution in the future

String.at(x, 2)

will return different characters than you are expecting, as the array starts at 0.

string = "There are many books"
String.split(string) |> Enum.map(fn word -> String.at(word, 2) end) |> Enum.join()
"eeno" # wrong

String.split(string) |> Enum.map(fn word -> String.at(word, 1) end) |> Enum.join()
"hrao" # correct
1 Like

why is Elixir not on this list?

What would be the content of each of those columns?

EDIT: OK, there are no arrays in Elixir… but still a fun list. Did’t imagine that there are so many 1-based languages out there.

1 Like
defmodule Homework do
  
  def second_letter_of_each_word("There are many books") do
    ["h", "r", "a", "o"]
  end
  
end

iex> Homework.second_letter_of_each_word("There are many books")
["h", "r", "a", "o"]

See if you can catch your prof sleeping… :joy:

2 Likes