Converting string in list of maps

Hi:

I’m a newbie in Elixir. I was trying to convert a key string value and while this works

grade =
  Enum.map(data, & &1["Grade"])
  |> Enum.map(fn n ->
    {v, _} = Float.parse(n)
    v
  end)

when I try to the same in a list of maps like this

list3 = Enum.map(list1, fn item -> %{
  name: item.name,
  date: item.date |> Timex.parse!("{M}/{D}/{YY}"),
  grade: item.grade |> Enum.map(fn x -> {v, _} = Float.parse(x); v end)
} end)

(list1, list3 are derived from data; details not essential)

I get error messages like this

** (Protocol.UndefinedError) protocol Enumerable not implemented for "65" of type BitString. This protocol is implemented for the following type(s): Arrays.Implementations.ErlangArray, Arrays.Implementations.MapArray, Date.Range, File.Stream, Function, GenEvent.Stream, HashDict, HashSet, IO.Stream, List, Map, MapSet, Range, Stream, Table.Mapper, Table.Zipper, Timex.Interval
    (elixir 1.14.0-dev) lib/enum.ex:1: Enumerable.impl_for!/1
    (elixir 1.14.0-dev) lib/enum.ex:166: Enumerable.reduce/3
    (elixir 1.14.0-dev) lib/enum.ex:4299: Enum.map/2

But

date: item.date |> Timex.parse!("{M}/{D}/{YY}"),

works fine.
Help is greatly appreciated!
Thx.

Hello,

In your first case, your first Enum.map returns a list of strings (the list composed of each data item’s Grade field). The List type does implement the Enumerable protocol, allowing you to use your second Enum.map on it to parse each of its items as Float.

In your second case, your second Enum.map is inside your first one. At this point you are manipulating an item variable which seems to be a Map or maybe a Struct. Your second Enum.map is applied on item.grade which (this time) is not a List, it’s just a string (and the BitString type does not implement the Enumerable protocol).

I guess that what you are trying to achieve is :

list3 = Enum.map(list1, fn item -> %{
  name: item.name,
  date: item.date |> Timex.parse!("{M}/{D}/{YY}"),
  grade: item.grade |> Float.parse() |> then(fn {v, _} -> v end)
} end)
1 Like

Thank you! It worked perfectly!
Gani-