Loading search index…
No recent searches
No results for "Query here"
module Main where import Prelude import Effect (Effect) import Effect.Console (log) import Data.Array (length, (!!), updateAt, replicate) import Data.Maybe (fromMaybe) main :: Effect Unit main = do -- Here we create an array `a` that will hold exactly 5 Ints. -- In PureScript, arrays are not fixed-length, but we can create -- one with 5 elements initialized to 0. let a = replicate 5 0 log $ "emp: " <> show a -- We can set a value at an index using the `updateAt` function, -- and get a value with the `!!` operator. let a' = fromMaybe a $ updateAt 4 100 a log $ "set: " <> show a' log $ "get: " <> show (fromMaybe 0 $ a' !! 4) -- The `length` function returns the length of an array. log $ "len: " <> show (length a') -- Use this syntax to declare and initialize an array in one line. let b = [1, 2, 3, 4, 5] log $ "dcl: " <> show b -- PureScript doesn't have a direct equivalent to Go's `...` syntax, -- but you can simply define the array with its elements. let b' = [1, 2, 3, 4, 5] log $ "dcl: " <> show b' -- PureScript doesn't have a direct equivalent to Go's index-based -- initialization, but you can achieve similar results with functions. let c = [100, 0, 0, 400, 500] log $ "idx: " <> show c -- Array types are one-dimensional, but you can compose types -- to build multi-dimensional data structures. let twoD = replicate 2 (replicate 3 0) let twoD' = [[0, 1, 2], [1, 2, 3]] log $ "2d: " <> show twoD' -- You can create and initialize multi-dimensional arrays at once too. let twoD'' = [[1, 2, 3], [1, 2, 3]] log $ "2d: " <> show twoD''
In PureScript, arrays are not fixed-length like in some other languages. However, we can still demonstrate similar concepts:
replicate
!!
Maybe
updateAt
length
To run this program, you would typically compile it with the PureScript compiler and then run it with Node.js:
$ pulp run emp: [0,0,0,0,0] set: [0,0,0,0,100] get: 100 len: 5 dcl: [1,2,3,4,5] dcl: [1,2,3,4,5] idx: [100,0,0,400,500] 2d: [[0,1,2],[1,2,3]] 2d: [[1,2,3],[1,2,3]]
This example demonstrates how to work with arrays in PureScript, showing initialization, accessing, modifying, and creating multi-dimensional arrays.