Title here
Summary here
PureScript uses recursive functions and higher-order functions for iteration instead of traditional for
loops. Here are some ways to achieve similar functionality:
module Main where
import Prelude
import Effect (Effect)
import Effect.Console (log)
main :: Effect Unit
main = do
-- The most basic type, with a single condition
let loop1 i =
if i <= 3
then do
log $ show i
loop1 (i + 1)
else pure unit
loop1 1
-- A classic initial/condition/after loop
let loop2 j =
if j < 3
then do
log $ show j
loop2 (j + 1)
else pure unit
loop2 0
-- Using `range` to iterate N times
traverse_ (\i -> log $ "range " <> show i) (0 .. 2)
-- Infinite loop with break
let infiniteLoop = do
log "loop"
pure unit -- In PureScript, we use `pure unit` instead of `break`
infiniteLoop
-- Using `filter` and `traverse_` to skip even numbers
traverse_ (\n -> log $ show n) $ filter (\n -> n `mod` 2 /= 0) (0 .. 5)
To run this program, you would typically compile it with the PureScript compiler and then run it with Node.js:
$ pulp run
1
2
3
0
1
2
range 0
range 1
range 2
loop
1
3
5
In PureScript:
traverse_
function is used to iterate over arrays and perform side effects.range
operator (..)
is used to create arrays of numbers.break
in PureScript. Instead, we control the flow with recursive calls and conditionals.filter
to skip elements in a sequence, similar to using continue
in imperative languages.PureScript’s functional approach to iteration can lead to more declarative and potentially safer code, as it avoids mutable state often associated with traditional for
loops.