Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Elixir - Cannot invoke remote function inside match

I'm working through a practice exercise on exercism and can't figure out why I'm getting the following error:

(CompileError) anagram.exs:19: cannot invoke remote function String.codepoints/1 inside match
(stdlib) lists.erl:1353: :lists.mapfoldl/3
(stdlib) lists.erl:1353: :lists.mapfoldl/3

I guess I'm not understanding pattern matching as well as I thought because I don't quite understand how I'm trying to call a remote function inside a match. Here are a couple examples of the test suite for context:

defmodule AnagramTest do
  use ExUnit.Case

test "no matches" do
  matches = Anagram.match "diaper", ["hello", "world", "zombies", "pants"]
  assert matches == []
end

test "detect simple anagram" do
  matches = Anagram.match "ant", ["tan", "stand", "at"]
  assert matches == ["tan"]
end

Here's my code:

defmodule Anagram do
  @doc """
  Returns all candidates that are anagrams of, but not equal to, 'base'.
  """
  @spec match(String.t, [String.t]) :: [String.t]
  def match(base, candidates) do
    base
    |> String.codepoints
    |> Enum.sort
    |> scan_for_matches(candidates)
  end

  defp scan_for_matches(base, candidates) do
    Enum.scan candidates, [], &(if analyze(&1, base), do: &2 ++ &1)
  end

  defp analyze(candidate, base) do
    candidate
    |> String.codepoints
    |> Enum.sort
    |> match?(base)
  end

  defp match?(candidate, base) do
    candidate == base
  end
end

Am I not just passing variables through to the analyze/2 function so that it ultimately returns a boolean? I appreciate any insight.

like image 748
jsonkenl Avatar asked Apr 23 '26 08:04

jsonkenl


1 Answers

This does need an answer, so I guess I'll add it in. match?/2 is a function exported from Kernel by default. You can override default imports via import Kernel, except: [match?: 2].

like image 77
asonge Avatar answered Apr 28 '26 18:04

asonge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!