aboutsummaryrefslogtreecommitdiff
path: root/src/client/Utils/List.elm
blob: 8e26e858ed204a88339112d30fac650c78972b58 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
module Utils.List exposing
  ( groupBy
  , mean
  , links
  )

import Dict
import Maybe.Extra as Maybe

groupBy : (a -> comparable) -> List a -> List (comparable, List a)
groupBy f xs =
  let addItem item dict =
        let groupItems = Dict.get (f item) dict |> Maybe.withDefault []
        in  Dict.insert (f item) (item :: groupItems) dict
  in  List.foldr addItem Dict.empty xs
        |> Dict.toList

mean : List Int -> Int
mean xs = (List.sum xs) // (List.length xs)

links : List a -> List (a, a)
links xs =
  let reversed = List.reverse xs
  in  List.foldr
        (\x acc ->
          case Maybe.map Tuple.first (List.head acc) of
            Just y ->
              (x, y) :: acc
            _ ->
              acc
        )
        (case reversed of
          x :: y :: _ -> [(y, x)]
          _ -> []
        )
        (List.reverse << List.drop 2 <| reversed)