Title here
Summary here
Our example demonstrates how to iterate over elements in various built-in data structures. Let’s see how to use range
with some of the data structures we’ve already learned.
Here we use for in
to sum the numbers in an array.
module Main where
import Prelude
import Effect (Effect)
import Effect.Console (log)
main :: Effect Unit
main = do
let nums = [2, 3, 4]
let sum = foldl (\acc num -> acc + num) 0 nums
log $ "sum: " <> show sum
for in
on arrays provides both the index and value for each entry. Above we didn’t need the index, so we ignored it with the _
placeholder. Sometimes we actually want the indexes though.
for (i <- indices nums) do
let num = nums # index i
when (num == Just 3) do
log $ "index: " <> show i
for in
on Map
iterates over key/value pairs.
let kvs = fromFoldable [Tuple "a" "apple", Tuple "b" "banana"]
for (Tuple k v <- toUnfoldable kvs) do
log $ k <> " -> " <> v
for in
can also iterate over just the keys of a Map
.
for (k <- keys kvs) do
log $ "key: " <> k
for in
on strings iterates over Unicode code points. The first value is the starting byte index of the Char
and the second the Char
itself.
for (Tuple i c <- toUnfoldable (zip (iterate add 0) "go")) do
log $ show i <> " " <> show c