bvobart

bvobart

How to define the type of a Stream with a specific type of elements?

For a list of integers, I can simply write a typespec like this:

@type foo() :: [integer()] # or list(integer())

But what about a Stream of integers?

There is no Stream.t() or Stream.t(element_type) and Enum.t() does not allow any type information about the elements. There is Enumerable.t(), which is what Stream.resource/3’s return type is typed as, and it accepts a type argument, so Enumerable.t(integer()) is a valid way of defining an Enumerable containing integers. However, that still equates to term() so it doesn’t give any type guarantees about the elements returned from the Enumerable or Enum functions.

Also, I want it to be clear to users of my functions that the function returns a Stream-like object where it is advisable to use Stream functions instead of Enum functions. Consider the following example:

defmodule MyApp.SomeStruct do
  @type t() :: __MODULE__{foo: integer(), bar: String.t()}
  defstruct foo: 0, bar: ""

  @doc """
  Stream a bunch of SomeStruct objects from a JSON lines file.
  """
  @spec stream(String.t()) :: Enumerable.t(t())
  def stream!(filename) do
    filepath |> File.stream!() |> Stream.map(fn line -> line |> JSON.decode!() |> decode() end)
  end

  @spec decode!(map()) :: t()
  def decode!(data) do
    %MyApp.SomeStruct{foo: data["foo"], bar: data["bar"]} # contrived example
  end
end

Currently, I use Enumerable.t(t()) instead of [t()] to indicate that we’re not returning a list, but more generically we’re returning an Enumerable. But actually, I want to say “hey this is a Stream, I recommend using Stream methods and only using an Enum method when you actually want to start consuming the items from this stream. Oh, and the items are of type t().

Is there currently a way in Elixir to write such a type? Or are there plans to support such a feature in Elixir’s type system?

Most Liked

al2o3cr

al2o3cr

IMO this highlights a big difference between “parameterized types” (the typespec system) and other systems like Rust’s generics.

Parameterized types are better thought of as compile-time functions that produce types. They always require fully-defined arguments and don’t support inference-like patterns.

For instance, you can’t write a signature like this:

# THIS DOES NOT WORK
@spec generic_filter(Enumerable.t(x), (x -> as_boolean(term()))) :: Enumerable.t(x)

Making a Stream.t(element_type) would also have the complication that there’s no obvious place to put element_type in the resulting %Stream{}; it’s not necessarily the type of the contained enum since funs are applied, and it’s only related to the top element of funs.

LostKobrakai

LostKobrakai

There cannot be any type guarantees for protocol implementations just like there cannot be type guarantees around behaviours. Dynamic dispatch cannot have correctness enforced at compile time for as long as valid implementations can be added at runtime – by adding additional modules.

Behaviour types all come down to module() and eventually atom() in typespecs, protocols can implemented for any term, so that’s what you ran into. If a provided atom actually references a module implementing an expected behaviour or if a given term has a related protocol implementation cannot be determined at compile time.

That’s imo a misunderstanding of the enumerable protocol. There is no stream just like there’s no “not a stream”. They’re all Enumerables, potentially infinite in length. The difference between Stream and Enum is not in the source data, the difference is in the processing / how they work over enumerables. And the caller decides to either process lazily (e.g. stream apis) or processes eagerly (e.g. enum apis).

LostKobrakai

LostKobrakai

Totally impossible given you can defmodule a new module at any time or replace an existing one – even at runtime. Most famously that’s how hot code updates work. The typesystem could make assumptions of no runtime created modules, but I wouldn’t expect that to happen.

Where Next?

Popular in Questions Top

sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
itssasanka
Hi all, Trying to get some more clarity over utc_datetime and naive_datetime for Ecto: https://hexdocs.pm/ecto/Ecto.Schema.html#module-...
New
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
chensan
I have a User schema with a :from_id field set to type :string: defmodule TweetBot.Repo.Migrations.CreateUsers do use Ecto.Migration ...
New
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New

Other popular topics Top

Qqwy
Update: How to use the Blogs & Podcasts section You can post links to your blog posts or podcasts either in one of the Official Blog...
3268 119930 1237
New
William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
axelson
This post is a wiki (feel free to hit the edit button near the bottom right of this post to add your own changes!) This post collects co...
239 45766 226
New
ovidiubadita
Hey all, I discovered Elixir and I love it. I always wanted to learn a functional programming and I intended to go for Haskell, but afte...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement