c13e

c13e OP

I’m learning Haskell at the moment and contrasting its semantics with Elixir as I go.

In Haskell, if I create the following naive & inefficient prime number checker:

factors n = [x | x <- [1..n], n `mod` x == 0]
prime n = factors n == [1, n]

and run it against a large number like 10^9, it returns False immediately thanks to lazy evaluation as soon as a mismatch occurs.

> prime 1000000000
False

If I do the same in Elixir, the eager evaluation will try to compute all the factors of 10^9 first, which is very slow with this implementation.

factor = &(for x <- 1..&1, rem(&1, x) == 0, do: x)
prime = &(factor.(&1) == [1, &1])
prime.(1000000000)
# hangs

The two evaluation strategies make sense to me but I somehow still find it surprising that the BEAM runtime can’t optimize away the matching against 2-element list and instead carries on the computation past the (sufficient) first 2 evaluations of factor.(1000000000).

I guess despite the eager evaluation, I was still expecting some sort of treacherous optimization from the BEAM :slight_smile:

Can someone enlighten me as to why this kind of constrained optimization can’t or doesn’t happen in languages with eager evaluation? Thanks!

First 3 of 3 Posts Switch mode

Qqwy

Qqwy

TypeCheck Core Team

Here is the code one more time, but now as more idiomatic Elixir with named functions in a module (rather than anonymous functions in IEx).

defmodule StrictExample do
  def factor(val) do
    for x <- 1..val, rem(val, x) == 0 do
      x
    end
  end

  def prime(val) do
    factor(val) == [1, val]
  end

  def is_large_number_prime() do
    prime(1000000000)
  end
end

It indeed has to do with the order of evaluation.
Haskell, being powered by a STG (Spineless Tagless graph-reduction machine), will move execution from the ‘goal’ back to where it originates.

In this example, it will indeed try to match [1, n] with the outcome of factors n. Indeed because of laziness is Haskell able to stop once two elements have been read from the output list of factor.

However, on the BEAM, we do not have this context-switching between looking at multiple parts of the output. Instead, for an operation like == we first evaluate both operands, and then check whether they are equal.

The optimization you expect here is (in eager languages) both rather limited in usefulness for practical applications, as well as rather high-level in the sense that as a human it seems obvious but for a compiler it would require many steps of intermediate reasoning.

To make an explicitly lazy implementation in Elixir, you can do this:

defmodule LazyExample do
  def factor(val) do
    # A lazy enumeration of all prime factors of `val`
    Stream.filter(1..val, &rem(val, &1) == 0)
  end

  def prime(val) do
    # We force the stream here, but only look at the first two elements.
    Enum.take(factor(val), 2) == [1, val]
  end

  def is_large_number_prime() do
    prime(1000000000)
  end
end

In this implementation, prime(1000000000) will indeed execute very fast.

c13e

c13e OP

Thank you so much for the clear explanation!

It makes more sense now given that such context switching strategy doesn’t happen in the BEAM or play well with eager evaluation in general.

Haskell’s STG sounds fascinating, will look into it :thinking:

kip

kip

ex_cldr Core Team

For those like my treading this path for the first time, here’s a good starting point: https://www.microsoft.com/en-us/research/wp-content/uploads/1992/04/spineless-tagless-gmachine.pdf

— All posts loaded —

Where Next? Top

Trending in Questions Top

stjefim
Hello! Suppose you are building workflow (order / task / payment) processing system with the following requirements: Each workflow con...
New
jonnycharles
I’m in search of an Elixir library that offers PDF generation capabilities similar to Ruby’s Prawn. While there have been discussions abo...
New
spammy
I’m looking to build a personal workflow to quickly deploy web applications written in elixir/phoenix, for local consumption (ie not on t...
New
dli
Before I dive in myself, did anyone successfully sprinkle Hologram into their existing LiveView app? Looking for hints regarding: Addi...
New
bottlenecked
Hi all, I wanted to ask how the community is dealing with post-release steps. Today we have Ecto migrations, which make sure that the db...
New
roeland
Kia ora, We have been using elixir-google-api to connect to Google Drive. However, with the updates to Tesla due to CVEs this is now bro...
New
michallepicki
I am using Oban and occasionally, shortly after a deployment, a handful of jobs can fail because of dependency on other parts of the syst...
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
juhalehtonen
There has been a thread to discuss the Stack Overflow Developer Survey on this forum every year since 2018, so here’s yet another one for...
New

We're in Beta

About us Mission Statement