Check if partial_id_list in full_id_list using Enum.map/2

I have a list of partial ids ie

[
  "12345-43",
  "435-422",
  "87655-12",
]

that I need to check to see if any of them match against another list of full ids ie

[
  "12345-43-02",
  "435-422-05",
  "87655-12-76",
]

the in/2 aka Enum.member/2 function does not check for partial matches and this always returns false because Membership is tested with the match (===/2) operator:

  Enum.map(partial_ids, fn partial_id ->
    if partial_id in full_id do
      true
    else
      false
    end
  end)

I tried adding a nested Enum.map/2 to be able to use =~ but then I get the return values for each entry. How would you go about solving this?

Are you trying to take the list of partial ids and return only those that match against full ids, or are you trying to see if any of the partial ids match any of the full ids?

iex> partials = [
  "12345-43",
  "435-422",
  "87655-12",
]
iex> fulls = [
  "12345-43-02",
  "435-422-05",
  "87655-12-76",
]
iex> for x <- partials, y <- fulls, String.starts_with?(y, x), do: IO.puts("#{x} -> #{y}")   
12345-43 -> 12345-43-02
435-422 -> 435-422-05
87655-12 -> 87655-12-76
[:ok, :ok, :ok]

This should give You the list of partials matching the start of any full ids.

2 Likes

I just want it to return true if the partial is in the full list or return false if it is not

Define ‘in’? Do you mean anywhere in it? Only at the start? Etc…?

@kokolegorille Did a for-comprehension based one for if it starts with it, an Enum version of the same for comparison would be:

iex(1)> partials = [
...(1)>   "12345-43",
...(1)>   "435-422",
...(1)>   "87655-12",
...(1)> ]
["12345-43", "435-422", "87655-12"]
iex(2)> fulls = [
...(2)>   "12345-43-02",
...(2)>   "435-422-05",
...(2)>   "87655-12-76",
...(2)> ]
["12345-43-02", "435-422-05", "87655-12-76"]
iex(3)> Enum.any?(partials, &Enum.any?(fulls, fn s -> String.starts_with?(s, &1) end))
true

And it’s not hard to adjust it to return what’s found or so either (either first or all).

3 Likes

If an entry in the partial exists anywhere in the full, I’d like to return true. I think you’ve given me what I’m looking for, thank you.

1 Like

I believe you should replace String.starts_with? with String.contains? because you seem to want a match anywhere in the full string as opposed to at the start.

2 Likes