]> Git — Sourcephile - gargantext.git/blob - src/Gargantext/Core/Utils.hs
Merge remote-tracking branch 'origin/adinapoli/issue-185-job-api' into dev-merge
[gargantext.git] / src / Gargantext / Core / Utils.hs
1 {-|
2 Module : Gargantext.Utils
3 Description :
4 Copyright : (c) CNRS, 2017-Present
5 License : AGPL + CECILL v3
6 Maintainer : team@gargantext.org
7 Stability : experimental
8 Portability : POSIX
9
10 Here is a longer description of this module, containing some
11 commentary with @some markup@.
12 -}
13
14
15 module Gargantext.Core.Utils (
16 -- module Gargantext.Utils.Chronos
17 module Gargantext.Core.Utils.Prefix
18 , something
19 , alphanum
20 , choices
21 , randomString
22 , groupWithCounts
23 , addTuples
24 ) where
25
26 import Data.Char (chr, ord)
27 import qualified Data.List as List
28 import Data.Maybe
29 import Data.Monoid
30 import Data.Text (Text, pack)
31 import Prelude ((!!))
32 import System.Random (initStdGen, uniformR)
33
34 -- import Gargantext.Utils.Chronos
35 import Gargantext.Core.Utils.Prefix
36 import Gargantext.Prelude
37
38
39 something :: Monoid a => Maybe a -> a
40 something Nothing = mempty
41 something (Just a) = a
42
43 alphanum :: [Char]
44 alphanum = (chr <$> digits) <> (chr <$> lowercase) <> (chr <$> uppercase)
45 where
46 digits = [(ord '0')..(ord '9')]
47 lowercase = [(ord 'a')..(ord 'z')]
48 uppercase = [(ord 'A')..(ord 'Z')]
49
50 choices :: Int -> [a] -> IO [a]
51 choices 0 _ = pure []
52 choices num lst = do
53 gen <- initStdGen
54 let (cIdx, _) = uniformR (0, length lst - 1) gen
55 c = lst !! cIdx
56 choices' <- choices (num - 1) lst
57 pure (c:choices')
58
59 randomString :: Int -> IO Text
60 randomString num = do
61 str <- choices num alphanum
62 pure $ pack str
63
64
65 -- | Given a list of items of type 'a', return list with unique items
66 -- (like List.nub) but tuple-d with their counts in the original list
67 groupWithCounts :: (Ord a, Eq a) => [a] -> [(a, Int)]
68 groupWithCounts = map f
69 . List.group
70 . List.sort
71 where
72 f [] = panic "[groupWithCounts] impossible"
73 f ts@(t:_) = (t, length ts)
74
75 addTuples :: (Num a, Num b) => (a, b) -> (a, b) -> (a, b)
76 addTuples (a1, b1) (a2, b2) = (a1 + a2, b1 + b2)