Skip to content

Commit

Permalink
Elixir library: add support to String.Chars protocol to Enum.join
Browse files Browse the repository at this point in the history
Now `Enum.join([1, 2, 3], ",")` is allowed.

Signed-off-by: Davide Bettio <davide@uninstall.it>
  • Loading branch information
bettio committed Sep 15, 2024
1 parent 664b2c1 commit 1f97456
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 3 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Elixir standard library modules
- ESP32: `--boot` option to mkimage.sh tool
- Add `erlang:atom_to_binary/1` that is equivalent to `erlang:atom_to_binary(Atom, utf8)`
- Support for Elixir `String.Chars` protocol
- Support for Elixir `String.Chars` protocol, now functions such as `Enum.join` are able to take
also non string parameters (e.g. `Enum.join([1, 2], ",")`
- Support for Elixir `Enum.at/3`

### Changed
Expand Down
11 changes: 9 additions & 2 deletions libs/exavmlib/lib/Enum.ex
Original file line number Diff line number Diff line change
Expand Up @@ -448,12 +448,12 @@ defmodule Enum do
end

@doc """
Joins the given enumerable into a binary using `joiner` as a
Joins the given `enumerable` into a binary using `joiner` as a
separator.
If `joiner` is not passed at all, it defaults to the empty binary.
All items in the enumerable must be convertible to a binary,
All elements in the `enumerable` must be convertible to a binary,
otherwise an error is raised.
## Examples
Expand All @@ -468,6 +468,12 @@ defmodule Enum do
@spec join(t, String.t()) :: String.t()
def join(enumerable, joiner \\ "")

def join(enumerable, "") do
enumerable
|> map(&entry_to_string(&1))
|> IO.iodata_to_binary()
end

def join(enumerable, joiner) when is_binary(joiner) do
reduced =
reduce(enumerable, :first, fn
Expand Down Expand Up @@ -669,6 +675,7 @@ defmodule Enum do
@compile {:inline, entry_to_string: 1, reduce: 3}

defp entry_to_string(entry) when is_binary(entry), do: entry
defp entry_to_string(entry), do: String.Chars.to_string(entry)

## drop

Expand Down
2 changes: 2 additions & 0 deletions tests/libs/exavmlib/Tests.ex
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ defmodule Tests do

# Enum.join
"1, 2, 3" = Enum.join(["1", "2", "3"], ", ")
"1, 2, 3" = Enum.join([1, 2, 3], ", ")
"123" = Enum.join([1, 2, 3], "")

# Enum.reverse
[4, 3, 2] = Enum.reverse([2, 3, 4])
Expand Down

0 comments on commit 1f97456

Please sign in to comment.