Building strings

A program builds text in one of three ways, and the choice is about cost. Interpolation and <> are for a line the code reads as one expression, Enum.join/2 is for a list of parts, and iodata is for a large text built in pieces: a nested list of binaries and bytes that becomes one binary only at the end. In Elixir a binary is immutable, so every addition copies what came before, and the third form is the one that does not.

Interpolation

#{} inside a double-quoted string calls to_string/1 on the value and puts the result in place. It is the form for a sentence with a value in it, and the value may be any expression:

interpolation.exs

name = "Ada" greeting = "Hello, #{name}!" IO.inspect(greeting) IO.inspect("Hello, " <> name <> "!") IO.inspect("2 + 2 = #{2 + 2}")

elixir interpolation.exs

"Hello, Ada!"
"Hello, Ada!"
"2 + 2 = 4"

The first two values are equal, and the second line shows the operator the interpolation compiles to: <> joins two binaries. An interpolation of a value that is not text calls the protocol rather than failing, so a number, an atom and a list with a text form all fit; <> requires a binary on both sides.

The <> operator

<> is the concatenation of two binaries, and a chain of it copies the left side at every step. For two or three parts that is invisible; for a loop it is the quadratic cost the list lesson showed with ++:

join.exs

words = ["one", "two", "three"] IO.inspect(Enum.join(words, ", ")) IO.inspect(Enum.join(words)) IO.inspect(Enum.join([1, 2, 3], "-"))

elixir join.exs

"one, two, three"
"onetwothree"
"1-2-3"

Enum.join/2 walks the list once and builds the result once, and it converts each item with to_string/1, which is why the numbers join without a call. A loop that writes acc <> line should write [acc | line] or a list of parts and call Enum.join/2 once at the end.

Iodata: a nested list of bytes

Iodata is a binary, a byte or a list of iodata, nested as deep as the program likes. IO.iodata_to_binary/1 flattens it into one binary in one pass, and IO.iodata_length/1 counts the bytes without building it:

iodata.exs

iodata = ["Hello, ", ["Ada", "!"], ?\n] IO.inspect(iodata) IO.inspect(IO.iodata_to_binary(iodata)) IO.inspect(IO.iodata_length(iodata))

elixir iodata.exs

["Hello, ", ["Ada", "!"], 10]
"Hello, Ada!\n"
12

The literal is a list of a binary, a nested list and a byte, and the inspector prints the newline as the integer 10 because that is what the item is. The conversion is the point: a program that appends to an iodata list with [part | iodata] pays one cell per part, and the single conversion at the end pays one pass over the bytes.

A text built by a function

The shape a report takes is a function that answers iodata for one row, and a list of those rows that becomes a binary once. The function below builds one line per score:

builder.exs

defmodule Report do def line(name, score) do ["- ", name, ": ", Integer.to_string(score), "\n"] end end lines = [Report.line("Ada", 9), Report.line("Bob", 7)] IO.puts(IO.iodata_to_binary(lines))

elixir builder.exs

- Ada: 9
- Bob: 7

The row is a list of five parts and the report is a list of rows, so the nesting is two levels deep and the conversion handles both. IO.puts/1 takes iodata directly, which is why the last line could drop the conversion; the explicit call is what a program writes when the binary is stored or sent rather than printed.

The mistake: <> with a number

The operator takes binaries and nothing else. A number on either side stops the program with an ArgumentError that names the segment and the value:

mistake.exs

count = 3 IO.puts("count: " <> count)

elixir mistake.exs

** (ArgumentError) construction of binary failed: segment 2 of type 'binary': expected a binary but got: 3
    mistake.exs:3: (file)
    (elixir 1.19.7) lib/code.ex:1613: Code.require_file/2

The fix is Integer.to_string(count) or an interpolation, "count: #{count}", which calls to_string/1 for the program. The message says segment 2 because the operator compiles to a bitstring construction, the same syntax the binaries lesson used, with one segment per side.

The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. Which form builds a large text in one pass over the parts?

    Answer

    an iodata list and one IO.iodata_to_binary/1 call

    The nested list holds the parts cheaply and one conversion writes the bytes once.

  2. Why is a loop with acc <> part quadratic?

    Answer

    Every step copies the whole of acc

    A binary is immutable, so each concatenation builds a new binary of the growing size.

  3. What does interpolation call on the value it inserts?

    Answer

    String.Chars.to_string/1 through the protocol

    The interpolation uses the String.Chars protocol, whose implementation for a value is to_string.

  4. Which value is not iodata?

    Answer

    a map

    Iodata is a binary, a byte or a list of iodata; a map is not part of it.

  5. What does this program print? IO.inspect("2 + 2 = #{2 + 2}")

    Answer

    "2 + 2 = 4"

    The braces hold an expression, and the number is put into the string.

  6. What does this program print? IO.inspect(Enum.join([1, 2], "-"))

    Answer

    "1-2"

    The items are converted to text and separated by the second argument.

  7. What does this program print? IO.inspect(IO.iodata_to_binary(["a", ["b"], ?c]))

    Answer

    "abc"

    The nested list flattens to the three bytes of a, b and c, and inspect shows the string.

  8. What does this program print? IO.inspect(IO.iodata_length(["ab", [?c]]))

    Answer

    3

    The length counts the bytes of all parts: two and one.

  9. What does this program print? IO.inspect(Enum.join(["a", "b"]))

    Answer

    "ab"

    Without a separator the parts are joined with nothing between them.

  10. What does this program do? count = 3 IO.puts("count: " <> count)

    Answer

    An ArgumentError, because the right side of <> is not a binary

    The operator takes binaries on both sides, and the number must be converted or interpolated.

Автор статьи: Arthur Isaev

Изображение баннера