-
Notifications
You must be signed in to change notification settings - Fork 23
/
List.hs
388 lines (334 loc) · 11.7 KB
/
List.hs
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# OPTIONS_GHC -fno-warn-orphans #-}
-- |
-- Module : Data.Massiv.Core.List
-- Copyright : (c) Alexey Kuleshevich 2018-2019
-- License : BSD3
-- Maintainer : Alexey Kuleshevich <lehins@yandex.ru>
-- Stability : experimental
-- Portability : non-portable
--
module Data.Massiv.Core.List
( LN
, L(..)
, Array(..)
, toListArray
, showsArrayPrec
, showArrayList
, ListItem
) where
import Control.Exception
import Control.Monad (unless, when)
import Control.Scheduler
import Data.Coerce
import Data.Foldable (foldr')
import qualified Data.List as L
import qualified Data.Massiv.Array.Manifest.Vector.Stream as S
import Data.Massiv.Core.Common
import Data.Typeable
import GHC.Exts
import System.IO.Unsafe (unsafePerformIO)
data LN
type family ListItem ix e :: * where
ListItem Ix1 e = e
ListItem ix e = [ListItem (Lower ix) e]
type instance NestedStruct LN ix e = [ListItem ix e]
newtype instance Array LN ix e = List { unList :: [Elt LN ix e] }
instance Construct LN Ix1 e where
setComp _ = id
{-# INLINE setComp #-}
makeArray _ (Sz n) f = coerce (fmap f [0 .. n - 1])
{-# INLINE makeArray #-}
makeArrayLinear _ (Sz n) f = coerce (fmap f [0 .. n - 1])
{-# INLINE makeArrayLinear #-}
instance {-# OVERLAPPING #-} Nested LN Ix1 e where
fromNested = coerce
{-# INLINE fromNested #-}
toNested = coerce
{-# INLINE toNested #-}
instance ( Elt LN ix e ~ Array LN (Lower ix) e
, ListItem ix e ~ [ListItem (Lower ix) e]
, Coercible (Elt LN ix e) (ListItem ix e)
) =>
Nested LN ix e where
fromNested = coerce
{-# INLINE fromNested #-}
toNested = coerce
{-# INLINE toNested #-}
instance Nested LN ix e => IsList (Array LN ix e) where
type Item (Array LN ix e) = ListItem ix e
fromList = fromNested
{-# INLINE fromList #-}
toList = toNested
{-# INLINE toList #-}
data L = L
type instance NestedStruct L ix e = Array LN ix e
data instance Array L ix e = LArray { lComp :: Comp
, lData :: !(Array LN ix e) }
instance Nested L ix e where
fromNested = LArray Seq
{-# INLINE fromNested #-}
toNested = lData
{-# INLINE toNested #-}
instance Nested LN ix e => IsList (Array L ix e) where
type Item (Array L ix e) = ListItem ix e
fromList = LArray Seq . fromNested
{-# INLINE fromList #-}
toList = toNested . lData
{-# INLINE toList #-}
instance {-# OVERLAPPING #-} Ragged L Ix1 e where
isNull = null . unList . lData
{-# INLINE isNull #-}
emptyR comp = LArray comp (List [])
{-# INLINE emptyR #-}
edgeSize = SafeSz . length . unList . lData
{-# INLINE edgeSize #-}
consR x arr = arr { lData = coerce (x : coerce (lData arr)) }
{-# INLINE consR #-}
unconsR LArray {..} =
case L.uncons $ coerce lData of
Nothing -> Nothing
Just (x, xs) -> Just (x, LArray lComp (coerce xs))
{-# INLINE unconsR #-}
flattenRagged = id
{-# INLINE flattenRagged #-}
generateRaggedM !comp !k f = do
xs <- loopDeepM 0 (< coerce k) (+ 1) [] $ \i acc -> do
e <- f i
return (e:acc)
return $ LArray comp $ coerce xs
{-# INLINE generateRaggedM #-}
loadRagged using uWrite start end sz xs =
using $ do
leftOver <-
loopM start (< end) (+ 1) xs $ \i xs' ->
case unconsR xs' of
Nothing -> return $! throw (DimTooShortException sz (outerLength xs))
Just (y, ys) -> uWrite i y >> return ys
unless (isNull leftOver) (return $! throw DimTooLongException)
{-# INLINE loadRagged #-}
raggedFormat f _ arr = L.concat $ "[ " : L.intersperse ", " (map f (coerce (lData arr))) ++ [" ]"]
instance (Index ix, Ragged L ix e) => Load L ix e where
size = coerce . edgeSize
{-# INLINE size #-}
getComp = lComp
{-# INLINE getComp #-}
loadArrayM scheduler arr uWrite =
loadRagged (scheduleWork scheduler) uWrite 0 (totalElem sz) sz arr
where !sz = edgeSize arr
{-# INLINE loadArrayM #-}
instance (Index ix, Load L ix e, Ragged L ix e) => Load LN ix e where
size = edgeSize . LArray Seq
{-# INLINE size #-}
getComp _ = Seq
{-# INLINE getComp #-}
loadArrayM scheduler arr uWrite =
loadRagged (scheduleWork scheduler) uWrite 0 (totalElem sz) sz arrL
where
!arrL = LArray Seq arr
!sz = size arrL
{-# INLINE loadArrayM #-}
outerLength :: Array L ix e -> Sz Int
outerLength = SafeSz . length . unList . lData
instance ( Index ix
, Index (Lower ix)
, Ragged L (Lower ix) e
, Elt L ix e ~ Array L (Lower ix) e
, Elt LN ix e ~ Array LN (Lower ix) e
, Coercible (Elt LN ix e) [Elt LN (Lower ix) e]
) =>
Ragged L ix e where
isNull = null . unList . lData
{-# INLINE isNull #-}
emptyR comp = LArray comp (List [])
{-# INLINE emptyR #-}
edgeSize arr =
SafeSz
(consDim (length (unList (lData arr))) $
case unconsR arr of
Nothing -> zeroIndex
Just (x, _) -> coerce (edgeSize x))
{-# INLINE edgeSize #-}
consR (LArray _ x) arr = newArr
where
newArr = arr {lData = coerce (x : coerce (lData arr))}
{-# INLINE consR #-}
unconsR LArray {..} =
case L.uncons (coerce lData) of
Nothing -> Nothing
Just (x, xs) ->
let newArr = LArray lComp (coerce xs)
newX = LArray lComp x
in Just (newX, newArr)
{-# INLINE unconsR #-}
-- generateRaggedM Seq !sz f = do
-- let !(k, szL) = unconsSz sz
-- loopDeepM 0 (< coerce k) (+ 1) (emptyR Seq) $ \i acc -> do
-- e <- generateRaggedM Seq szL (\ !ixL -> f (consDim i ixL))
-- return (cons e acc)
generateRaggedM = unsafeGenerateParM
{-# INLINE generateRaggedM #-}
flattenRagged arr = LArray {lComp = lComp arr, lData = coerce xs}
where
xs = concatMap (unList . lData . flattenRagged . LArray (lComp arr)) (unList (lData arr))
{-# INLINE flattenRagged #-}
loadRagged using uWrite start end sz xs = do
let (k, szL) = unconsSz sz
step = totalElem szL
isZero = totalElem sz == 0
when (isZero && not (isNull (flattenRagged xs))) (return $! throw DimTooLongException)
unless isZero $ do
leftOver <-
loopM start (< end) (+ step) xs $ \i zs ->
case unconsR zs of
Nothing -> return $! throw (DimTooShortException k (outerLength xs))
Just (y, ys) -> do
_ <- loadRagged using uWrite i (i + step) szL y
return ys
unless (isNull leftOver) (return $! throw DimTooLongException)
{-# INLINE loadRagged #-}
raggedFormat f sep (LArray comp xs) =
showN (\s y -> raggedFormat f s (LArray comp y :: Array L (Lower ix) e)) sep (coerce xs)
unsafeGenerateParM ::
(Elt LN ix e ~ Array LN (Lower ix) e, Index ix, Monad m, Ragged L (Lower ix) e)
=> Comp
-> Sz ix
-> (ix -> m e)
-> m (Array L ix e)
unsafeGenerateParM comp !sz f = do
res <- sequence $ unsafePerformIO $ do
let !(ksz, szL) = unconsSz sz
!k = unSz ksz
withScheduler comp $ \ scheduler ->
splitLinearly (numWorkers scheduler) k $ \ chunkLength slackStart -> do
loopM_ 0 (< slackStart) (+ chunkLength) $ \ !start ->
scheduleWork scheduler $ do
res <- loopDeepM start (< (start + chunkLength)) (+ 1) [] $ \i acc ->
return (fmap lData (generateRaggedM Seq szL (\ !ixL -> f (consDim i ixL))):acc)
return $! sequence res
when (slackStart < k) $
scheduleWork scheduler $ do
res <- loopDeepM slackStart (< k) (+ 1) [] $ \i acc ->
return (fmap lData (generateRaggedM Seq szL (\ !ixL -> f (consDim i ixL))):acc)
return $! sequence res
return $ LArray comp $ List $ concat res
{-# INLINE unsafeGenerateParM #-}
instance {-# OVERLAPPING #-} Construct L Ix1 e where
setComp c arr = arr { lComp = c }
{-# INLINE setComp #-}
makeArray comp sz f = LArray comp $ List $ unsafePerformIO $
withScheduler comp $ \scheduler ->
loopM_ 0 (< coerce sz) (+ 1) (scheduleWork scheduler . return . f)
{-# INLINE makeArray #-}
instance ( Index ix
, Ragged L ix e
, Ragged L (Lower ix) e
, Elt L ix e ~ Array L (Lower ix) e
) =>
Construct L ix e where
setComp c arr = arr {lComp = c}
{-# INLINE setComp #-}
makeArray = unsafeGenerateN
{-# INLINE makeArray #-}
-- TODO: benchmark against using unsafeGenerateM directly
unsafeGenerateN ::
( Ragged r ix e
, Ragged r (Lower ix) e
, Elt r ix e ~ Array r (Lower ix) e )
=> Comp
-> Sz ix
-> (ix -> e)
-> Array r ix e
unsafeGenerateN comp sz f = unsafePerformIO $ do
let !(m, szL) = unconsSz sz
xs <- withScheduler comp $ \scheduler ->
loopM_ 0 (< coerce m) (+ 1) $ \i -> scheduleWork scheduler $
generateRaggedM comp szL $ \ix -> return $ f (consDim i ix)
return $! foldr' consR (emptyR comp) xs
{-# INLINE unsafeGenerateN #-}
-- | Construct an array backed by linked lists from any source array
--
-- @since 0.4.0
toListArray :: (Construct L ix e, Source r ix e)
=> Array r ix e
-> Array L ix e
toListArray !arr = makeArray (getComp arr) (size arr) (unsafeIndex arr)
{-# INLINE toListArray #-}
instance (Ragged L ix e, Show e) => Show (Array L ix e) where
showsPrec = showsArrayLAsPrec (Proxy :: Proxy L)
instance (Ragged L ix e, Show e) => Show (Array LN ix e) where
show arr = " " ++ raggedFormat show "\n " arrL
where arrL = fromNested arr :: Array L ix e
showN :: (String -> a -> String) -> String -> [a] -> String
showN _ _ [] = "[ ]"
showN fShow lnPrefix ls =
L.concat
(["[ "] ++
L.intersperse (lnPrefix ++ ", ") (map (fShow (lnPrefix ++ " ")) ls) ++ [lnPrefix, "]"])
showsArrayLAsPrec ::
forall r ix e. (Ragged L ix e, Typeable r, Show e)
=> Proxy r
-> Int
-> Array L ix e -- Array to show
-> ShowS
showsArrayLAsPrec pr n arr =
opp .
("Array " ++) .
showsTypeRep (typeRep pr) .
(' ':) .
showsPrec 1 (getComp arr) . (" (" ++) . shows (size arr) . (")\n" ++) . shows lnarr . clp
where
(opp, clp) =
if n == 0
then (id, id)
else (('(':), ("\n)" ++))
lnarr = toNested arr
-- | Helper function for declaring `Show` instances for arrays
--
-- @since 0.4.0
showsArrayPrec ::
forall r r' ix ix' e. (Ragged L ix' e, Load r ix e, Source r' ix' e, Show e)
=> (Array r ix e -> Array r' ix' e) -- ^ Modifier
-> Int
-> Array r ix e -- Array to show
-> ShowS
showsArrayPrec f n arr = showsArrayLAsPrec (Proxy :: Proxy r) n larr
where
arr' = f arr
larr = makeArray (getComp arr') (size arr') (evaluate' arr') :: Array L ix' e
-- | Helper function for declaring `Show` instances for arrays
--
-- @since 0.4.0
showArrayList
:: Show arr => [arr] -> String -> String
showArrayList arrs = ('[':) . go arrs . (']':)
where
go [] = id
go [x] = (' ':) . shows x . ('\n':)
go (x:xs) = (' ':) . shows x . ("\n," ++) . go xs
instance {-# OVERLAPPING #-} OuterSlice L Ix1 e where
unsafeOuterSlice (LArray _ xs) = (coerce xs !!)
{-# INLINE unsafeOuterSlice #-}
instance Ragged L ix e => OuterSlice L ix e where
unsafeOuterSlice arr' i = go 0 arr'
where
go n arr =
case unconsR arr of
Nothing -> throw $ IndexOutOfBoundsException (Sz (headDim (unSz (size arr')))) i
Just (x, _) | n == i -> x
Just (_, xs) -> go (n + 1) xs
{-# INLINE unsafeOuterSlice #-}
instance Stream LN Ix1 e where
toStream = S.fromList . coerce
{-# INLINE toStream #-}
instance Ragged L ix e => Stream L ix e where
toStream = S.fromList . coerce . lData . flattenRagged
{-# INLINE toStream #-}