@@ -32,6 +32,7 @@ module Data.Array
32
32
, toUnfoldable
33
33
, singleton
34
34
, (..), range
35
+ , rangeWithStep
35
36
, replicate
36
37
, some
37
38
, many
@@ -87,6 +88,8 @@ module Data.Array
87
88
, scanl
88
89
, scanr
89
90
91
+ , sliding
92
+ , slidingWithSizeAndStep
90
93
, sort
91
94
, sortBy
92
95
, sortWith
@@ -1289,3 +1292,72 @@ unsafeIndex :: forall a. Partial => Array a -> Int -> a
1289
1292
unsafeIndex = unsafeIndexImpl
1290
1293
1291
1294
foreign import unsafeIndexImpl :: forall a . Array a -> Int -> a
1295
+
1296
+ -- | Takes an arrays of length n and returns an array of Tuples with length n-1.
1297
+ -- | It's a "sliding window" view of this array with a window size of 2 and a step size of 1.
1298
+ -- |
1299
+ -- | ```purescript
1300
+ -- | sliding [1,2,3,4,5] = [(Tuple 1 2),(Tuple 2 3),(Tuple 3 4),(Tuple 4 5)]
1301
+ -- | ```
1302
+ -- |
1303
+ sliding :: forall a . Array a -> Array (Tuple a a )
1304
+ sliding l = zip l (drop 1 l)
1305
+
1306
+ -- | Takes an arrays and returns an array of arrays as a "sliding window" view of this array.
1307
+ -- | Illegal arguments result in an empty Array.
1308
+ -- |
1309
+ -- | ```purescript
1310
+ -- | > import Data.Array (range)
1311
+ -- | > slidingWithSizeAndStep 3 2 (range 0 10) = [[0,1,2],[2,3,4],[4,5,6],[6,7,8],[8,9,10],[10]]
1312
+ -- | > slidingWithSizeAndStep 3 3 (range 0 10) = [[0,1,2],[3,4,5],[6,7,8],[9,10]]
1313
+ -- | ```
1314
+ -- |
1315
+ slidingWithSizeAndStep :: forall a . Int -> Int -> Array a -> Array (Array a )
1316
+ slidingWithSizeAndStep size step array =
1317
+ let
1318
+ maxIndex = (length array) - 1
1319
+
1320
+ indices = rangeWithStep 0 maxIndex step
1321
+
1322
+ isValid = size > 0 && step > 0
1323
+ in
1324
+ if isValid then
1325
+ indices <#> \i -> slice i (i + size) array
1326
+ else
1327
+ []
1328
+
1329
+ -- | Create an array containing a range of integers with a given step size, including both endpoints.
1330
+ -- | Illegal arguments result in an empty Array.
1331
+ -- |
1332
+ -- | ```purescript
1333
+ -- | > rangeWithStep 0 6 2 = [0,2,4,6]
1334
+ -- | > rangeWithStep 0 (-6) (-2) = [0,-2,-4,-6]
1335
+ -- | ```
1336
+ -- |
1337
+ rangeWithStep :: Int -> Int -> Int -> Array Int
1338
+ rangeWithStep start endIndex step =
1339
+ let
1340
+ isValid =
1341
+ step /= 0
1342
+ && if endIndex >= start then
1343
+ step > 0
1344
+ else
1345
+ step < 0
1346
+
1347
+ hasReachedEnd curr =
1348
+ if step > 0 then
1349
+ curr > endIndex
1350
+ else
1351
+ curr < endIndex
1352
+
1353
+ helper :: Int -> Array Int -> Array Int
1354
+ helper currentIndex acc =
1355
+ if hasReachedEnd currentIndex then
1356
+ acc
1357
+ else
1358
+ helper (currentIndex + step) (snoc acc currentIndex)
1359
+ in
1360
+ if isValid then
1361
+ helper start []
1362
+ else
1363
+ []
0 commit comments