As you can see from the posted code I am quite new to Elixir but I figured this is the sort of thing people always have a hard time getting used to in a new language so it could be valuable to the community if someone would (over)explain what is happening here.
iex(4)> 'a' == 'b'
false
iex(5)> 'a' == 'a'
true
iex(6)> Enum.count('abcaa', fn(x) -> x == 'a' end)
0
iex(20)> Enum.count('abcaa', fn(x) -> x == to_charlist 'a' end)
0
iex(21)> Enum.count('abcaa', fn(x) -> to_charlist 'a' == x end)
5
iex(22)> Enum.count('abcaa', fn(x) -> 'a' == x end)
0
iex(23)> Enum.count('abcaa', fn(x) -> 97 == x end)
3
iex(24)> Enum.count('abcaa', fn(x) -> x == 97 end)
3
iex(25)> Enum.count('abcaa', fn(x) -> x == byte_size 'a' end)
** (ArgumentError) argument error
:erlang.byte_size('a')
(stdlib) erl_eval.erl:670: :erl_eval.do_apply/6
(stdlib) erl_eval.erl:470: :erl_eval.expr/5
(elixir) lib/enum.ex:492: anonymous fn/3 in Enum.count/2
(elixir) lib/enum.ex:2843: Enumerable.List.reduce/3
(elixir) lib/enum.ex:491: Enum.count/2
iex(25)> strand = 'a'
'a'
iex(26)> Enum.count('abcaa', fn(x) -> x == ^strand end)
** (CompileError) iex:26: cannot use ^strand outside of match clauses
(stdlib) lists.erl:1354: :lists.mapfoldl/3
(stdlib) lists.erl:1355: :lists.mapfoldl/3
(elixir) src/elixir_fn.erl:33: anonymous fn/3 in :elixir_fn.expand/3
iex(26)> Enum.count('abcaa', fn(x) -> x = ^strand end)
** (CompileError) iex:26: cannot use ^strand outside of match clauses
(elixir) src/elixir_fn.erl:33: anonymous fn/3 in :elixir_fn.expand/3
(stdlib) lists.erl:1239: :lists.map/2
(elixir) src/elixir_fn.erl:36: :elixir_fn.expand/3
(stdlib) lists.erl:1354: :lists.mapfoldl/3
iex(26)> Enum.count('abcaa', fn(x) -> ^strand = x end)
** (MatchError) no match of right hand side value: 97
As may be apparent to some of you I am solving Exercism problem number 2 in the Elixir track so I will get suggestions on how to improve my code there but I’d also like to upgrade my mental model of what is happening when I use Enum with anon functions and know how to compare [char] or char properly. Hence this topic.
Thank you!
Edit: I forgot to put the solution I ended up using:
iex(30)> Enum.count('abcaa', fn(x) -> x == List.first 'a' end)
3
Edit2: I can’t mark more than one post as the solution but both answers have value!