What have you tried? You’re asking community members to do work for you and this community is incredibly helpful. But in return, it is appropriate to at least show what you’ve tried already.
What you need is very easily achievable with the functions in the String and Enum module. Give it a try and post again if you succeed partially but can’t quite get there.
defmodule Main do
def names(phrase) do
var = String.split(phrase)
end
def loop(var) do
Enum.map(var, fn x ->
String.at(x, 2)
end)
end
end
Main.names("there is good a good pizza parlor")
|> IO.inspect()
defmodule Main do
def names(phrase) do
var = String.split(phrase)
end
def loop(var) do
Enum.map(var, fn x ->
String.at(x, 2)
end)
end
end
Main.names("there is good a good pizza parlor")
|> IO.inspect()
loop is never called (and its not a loop, you should spend some time to grasp the basics of functional languages, highly recommended: https://exercism.org - Elixir track).
You are nearly there.
iex(6)> phrase = "There are many books"
"There are many books"
iex(8)> var = String.split(phrase)
["There", "are", "many", "books"]
iex(9)> Enum.map(var, fn x ->
...(9)> String.at(x, 2)
...(9)> end)
["e", "e", "n", "o"]
Thanks for showing your work. You’ve made a good start. A few things to help get you a bit closer:
String.split/1 will split on Unicode whitespace. That’s a reasonable default for Latin text. If you are working with difference languages it won’t be the correct approach. If you need a more complete “split at words” implementation you can look this library.
Binary pattern matching is very good in elixir and matches can be put into function heads. Binary pattern matching is the fastest way to extract known parts of a string. For example:
iex> <<first::utf8, second::utf8, _rest::binary>> = "there"
"there"
iex> second
104
You’ll notice that second is 104 which is the code point of “h”. You can convert that back to a string if you need with List.to_string([second]) but in many cases you don’t need to do that. It depends.
iex> List.to_string([second])
"h"
Putting it together and returning the first letter if the word is one char long:
defmodule Names do
def names(names) do
names
|> String.split()
|> Enum.map(&extract_second/1)
|> List.to_string()
end
def extract_second(<<_first::utf8, second::utf8, _rest::binary>>), do: second
def extract_second(<<first::utf8>>), do: first
end
Example:
iex> Names.names "there is good a good pizza parlor"
"hsoaoia"
@Sebb’s answer will work perfectly well. My answer isn’t really all that much different - but the difference is a very valuable piece of Erlang/Elixir which is binary pattern matching.
Its a good thing to get familiar with as you get more comfortable with Elixir. And I am more than happy (as I’m sure others are) to explain any “head explosion” parts