Array.purs 2.41 KB
Newer Older
1 2 3 4
module Gargantext.Data.Array
  where

import Data.Array as DA
5
import Data.Array ((..))
6
import Data.List as List
7
import Data.Maybe
8
import Data.Sequence as Seq
9
import Data.Tuple (Tuple(..))
10
import Prelude
11

12 13
----------------------------------------------------------------------
-- | Split arrays tools
14 15 16 17 18 19 20
splitEvery :: forall a. Int -> Array a -> Array (Array a)
splitEvery _ [] = []
splitEvery n xs =
  let (Tuple h t) = splitAt n xs
  in DA.cons h (splitEvery n t)

splitAt :: forall a. Int -> Array a -> Tuple (Array a) (Array a)
21
splitAt n ls = Tuple (Seq.toUnfoldable x) (Seq.toUnfoldable xs)
22
  where
23
    Tuple x xs = Seq.splitAt n (Seq.fromFoldable ls)
24

25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
----------------------------------------------------------------------
-- | Array with Maybe tools
mapMaybe :: forall a b. (a -> Maybe b) -> Array a -> Array b
mapMaybe f = concatMap (maybe [] singleton <<< f)

catMaybes :: forall a. Array (Maybe a) -> Array a
catMaybes = mapMaybe identity

----------------------------------------------------------------------
-- | Array misc tools
concatMap :: forall a b. (a -> Array b) -> Array a -> Array b
concatMap = flip bind

singleton :: forall a. a -> Array a
singleton a = [a]

41 42 43 44 45 46 47
----------------------------------------------------------------------
-- | Seq with Maybe tools
seqMapMaybe :: forall a b. (a -> Maybe b) -> Seq.Seq a -> Seq.Seq b
seqMapMaybe f = seqConcatMap (maybe Seq.empty Seq.singleton <<< f)

seqCatMaybes :: forall a. Seq.Seq (Maybe a) -> Seq.Seq a
seqCatMaybes = seqMapMaybe identity
48

49 50 51 52
----------------------------------------------------------------------
-- | Seq misc tools
seqConcatMap :: forall a b. (a -> Seq.Seq b) -> Seq.Seq a -> Seq.Seq b
seqConcatMap = flip bind
53 54 55 56 57 58 59 60 61 62

-- swap 2 array indices
swap :: forall a. Int -> Int -> Array a -> Array a
swap i j arr = DA.updateAtIndices updates arr
  where
    updates = case DA.index arr i of
      Nothing -> []
      Just iEl -> case DA.index arr j of
        Nothing -> []
        Just jEl -> [ Tuple i jEl, Tuple j iEl ]
63

64 65 66
swapList :: forall a. Int -> Int -> List.List a -> List.List a
swapList i j seq = List.fromFoldable $ swap i j $ List.toUnfoldable seq

67
swapSeq :: forall a. Int -> Int -> Seq.Seq a -> Seq.Seq a
68
swapSeq i j seq = Seq.fromFoldable $ swap i j $ Seq.toUnfoldable seq
69 70 71 72 73 74

slidingWindow :: forall a. Array a -> Int -> Array (Array a)
slidingWindow lst len =
  let diff = DA.length lst - len
  in
   if diff < 0 then []
75
   else (\idx -> DA.slice idx (idx + len) lst) <$> 0 .. diff