Skip to content

Commit fd18b6a

Browse files
committed
Fix String.replace/4 typespec
Signed-off-by: Eric Meadows-Jönsson <[email protected]>
1 parent 4c9c95f commit fd18b6a

File tree

1 file changed

+8
-8
lines changed

1 file changed

+8
-8
lines changed

lib/elixir/lib/string.ex

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -74,21 +74,21 @@ defmodule String do
7474
be avoided in favor of binary functions or pattern matching.
7575
For example, imagine you have a string `prefix` and you want to
7676
remove this prefix from another string named `full`.
77-
77+
7878
One may be tempted to write:
79-
79+
8080
iex> take_prefix = fn full, prefix ->
8181
...> base = String.length(prefix)
8282
...> String.slice(full, base, String.length(full) - base)
8383
...> end
8484
...> take_prefix.("Mr. John", "Mr. ")
8585
"John"
86-
86+
8787
Although the function above works, it performs poorly. To
8888
calculate the length of the string, we need to traverse it
8989
fully, so we traverse both `prefix` and `full` strings, then
9090
slice the `full` one, traversing it again.
91-
91+
9292
A first attempting at improving it could be with ranges:
9393
9494
iex> take_prefix = fn full, prefix ->
@@ -103,7 +103,7 @@ defmodule String do
103103
extract a substring from a string, we can use `byte_size/1`
104104
and `binary_part/3` as there is no chance we will slice in
105105
the middle of a codepoint made of more than one byte:
106-
106+
107107
iex> take_prefix = fn full, prefix ->
108108
...> base = byte_size(prefix)
109109
...> binary_part(full, base, byte_size(full) - base)
@@ -112,7 +112,7 @@ defmodule String do
112112
"John"
113113
114114
Or simply used pattern matching:
115-
115+
116116
iex> take_prefix = fn full, prefix ->
117117
...> base = byte_size(prefix)
118118
...> <<_ :: binary-size(base), rest :: binary>> = full
@@ -672,8 +672,8 @@ defmodule String do
672672
"a[,,]b[,,]c"
673673
674674
"""
675-
@spec replace(t, t, t) :: t
676-
@spec replace(t, t, t, Keyword.t) :: t
675+
@spec replace(t, t | Regex.t, t) :: t
676+
@spec replace(t, t | Regex.t, t, Keyword.t) :: t
677677

678678
def replace(subject, pattern, replacement, options \\ []) when is_binary(replacement) do
679679
if Regex.regex?(pattern) do

0 commit comments

Comments
 (0)