Yes, just figured it out
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?
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
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.
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…