Purescript - iterate a longish array

68 Views Asked by At

The following code, being executed in Chrome, fails after printing 7492:

module Main where

import Prelude
import Effect (Effect)
import Effect.Console as Console
import Data.Array as Array
import Data.Traversable (for_)

main :: Effect Unit
main = do
  for_ (Array.range 1 10000) Console.logShow

What am I doing wrong here? How can I iterate over longer arrays without causing a stack overflow?

The code is compiled using spago build and runs using parcel.

Fragment of package.json:

  "devDependencies": {
    "parcel": "2.7.0",
    "purescript": "^0.15.4",
    "spago": "^0.20.9"
  }

UPD: In Orion, execution interrupts after 33793 iterations. Safari reaches 8000, getting slower and slower. This is on the "production" build of the script — spago bundle-app --to prod/index.js && parcel build prod/index.html.

2

There are 2 best solutions below

0
Mikhail Brinchuk On
Effect.foreachE (Array.range 1 100000) Console.logShow

seems to be working.

0
ゆきくらげ - Yukikurage On

The Control.Safely module provides a stack-safe for_.

import Control.Safely (for_)

main :: Effect Unit
main = do
  for_ (Array.range 1 10000) Console.logShow

This for_ can be applied to a monad that is an instance of MonadRec, where Effect is that instance.