File: ExtList.hs

package info (click to toggle)
haskell-basement 0.0.16-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 1,044 kB
  • sloc: haskell: 11,336; ansic: 63; makefile: 2
file content (47 lines) | stat: -rw-r--r-- 987 bytes parent folder | download | duplicates (5)
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
37
38
39
40
41
42
43
44
45
46
47
{-# LANGUAGE CPP #-}
module Basement.Compat.ExtList
    ( length
    , null
    , sum
    , reverse
    , (!!)
    ) where

import Basement.Compat.Base
import Basement.Numerical.Additive
import Basement.Types.OffsetSize
import qualified GHC.List as List

-- | Compute the size of the list
length :: [a] -> CountOf a
#if MIN_VERSION_base(4,8,0)
length = CountOf . List.foldl' (\c _ -> c+1) 0
#else
length = CountOf . loop 0
  where loop !acc []     = acc
        loop !acc (_:xs) = loop (1+acc) xs
#endif

null :: [a] -> Bool
null []    = True
null (_:_) = False

-- | Sum the element in a list
sum :: Additive n => [n] -> n
sum []     = azero
sum (i:is) = loop i is
  where
    loop !acc [] = acc
    loop !acc (x:xs) = loop (acc+x) xs
    {-# INLINE loop #-}

reverse :: [a] -> [a]
reverse l =  go l []
  where
    go []     acc = acc
    go (x:xs) acc = go xs (x:acc)

(!!) :: [a] -> Offset a -> a
[]    !! _  = error "invalid offset for !!"
(x:_) !! 0  = x
(_:xs) !! i = xs !! pred i