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

import Data.Array as DA
5
import Data.List as List
6
import Data.Maybe
7
import Data.Sequence as Seq
8
import Data.Tuple (Tuple(..))
9
import Prelude (bind, flip, identity, (<<<), ($))
10

11 12
----------------------------------------------------------------------
-- | Split arrays tools
13 14 15 16 17 18 19
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)
20
splitAt n ls = Tuple (Seq.toUnfoldable x) (Seq.toUnfoldable xs)
21
  where
22
    Tuple x xs = Seq.splitAt n (Seq.fromFoldable ls)
23

24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
----------------------------------------------------------------------
-- | 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]

40 41 42 43 44 45 46
----------------------------------------------------------------------
-- | 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
47

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

-- 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 ]
62

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

66
swapSeq :: forall a. Int -> Int -> Seq.Seq a -> Seq.Seq a
67
swapSeq i j seq = Seq.fromFoldable $ swap i j $ Seq.toUnfoldable seq