'Elixir Iterate over a list and append values from it to a new list

I need to parse some values from a list then recalculate them to a new one, how can that be done in elixir?

def calc_points(hand) do
    value = []
    
        for i <- hand do
            var = String.at(i,0)
            {val,_} = Integer.parse(var)
            value = [val| value]
            puts(Enum.sum(value))
        end
end

Where hand is ["6 of spades", "6 of suites"] Result should return a new list where the first characters of string are integers



Solution 1:[1]

It is helpful if your question includes sample input and desired output.

In Elixir, you will hear that "everything is an assignment". What that means is that you can't do the standard object-oriented thing and initiate a value up top and then modify it from within a loop. Instead, you need to rely on the building-blocks of functional programming: map and reduce.

The question you need to ask is whether or not the resulting list has the same number of elements as the incoming list. If so, then Enum.map/2 should be used to "transform" the elements of the list. E.g.

iex> hand = ["6 of spades", "8 of hearts", "4 of diamonds"]
iex> Enum.map(hand, fn <<first_char::binary-size(1)>> <> _ -> String.to_integer(first_char) end)
[6, 8, 4]

Note that the above example grabs the first character of the string by specifying ::binary-size(1) after the variable name. This won't work if your hand contains strings like 12 of hearts or K of diamonds, the former because it's 2 chars, the latter because a letter won't convert to an integer.

If the resulting list will have a different number of elements as the incoming list, then you will likely use Enum.reduce/3.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1