Author Bitonic at English Wikipedia (CC0 1.0)

Code Snippets

Data/Bitonic.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
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE Safe       #-}

--------------------------------------------------------------------------------

module Data.Bitonic
  ( Sortable
  , SortableTrust
  , sort
  )
where

--------------------------------------------------------------------------------

import           Data.Bits
  ( countLeadingZeros
  , finiteBitSize
  , shiftL
  , shiftR
  , (.&.)
  )
import qualified Foreign.Marshal.Alloc as FFI
import           Foreign.Ptr
  ( Ptr
  , plusPtr
  )
import           Foreign.Storable
  ( Storable
  )
import qualified Foreign.Storable      as FFI

--------------------------------------------------------------------------------

-- To prevent the users from adding instances of `ForeignMemoryInterface`, we
-- provide a middle-layer (`FMEMI`) between the `Monad` instance and the `Proxy`
-- (`ForeignMemoryInterface`) instance.
--
-- Note: This is redundant as by using `RankNTypes` to create a type alias and
-- expose that type from the module instead.

class Monad m => FMEMI                  m
class FMEMI m => ForeignMemoryInterface m where
  malloc :: Storable a => Int   ->             m (Ptr a)
  free   :: Storable a => Ptr a ->             m (     )
  peek   :: Storable a => Ptr a -> Int ->      m      a
  poke   :: Storable a => Ptr a -> Int -> a -> m (     )

--------------------------------------------------------------------------------

type Sortable a io =
  ( Storable a
  , Ord a
  , ForeignMemoryInterface io
  ) => [a] -> io [a]

type SortableTrust a =
  ( Storable a
  , Ord a
  ) => [a] -> [a]

type OffSet = Int
type Length = Int

--------------------------------------------------------------------------------

instance FMEMI                  IO
instance ForeignMemoryInterface IO where
  malloc = FFI.mallocBytes
  free   = FFI.free
  peek   = FFI.peekElemOff
  poke   = FFI.pokeElemOff

--------------------------------------------------------------------------------

sort :: Sortable a io
sort [       ] = pure []
sort xs@(hd:_) =
  malloc     m  >>= \ p  ->
  store  p 0 ys >>= \ _  -> -- initiate memory values to the list max value
  store  p 0 xs >>= \ _  ->
  sorter p o n  >>= \ _  ->
  query  p n    >>= \ zs ->
  free   p      >>= \ _  ->
  pure $ take l zs
  where
    l  = length xs
    n  = pow2 l -- Ensure that allocated memory is 2^i
    o  = FFI.sizeOf hd
    m  = n * o
    ys = take n $ cycle [ foldl1 max xs ]

--------------------------------------------------------------------------------

query
  ::
    ( Storable a
    , ForeignMemoryInterface io
    )
  => Ptr a
  -> Length
  -> io [a]
query p n =
  aux 0
  where
    aux i
      | i   <   n =
        aux (i+1) >>= \ tl ->
        peek p i  >>= \ hd ->
        pure $ hd:tl
      | otherwise = pure []

store
  ::
    ( Storable a
    , ForeignMemoryInterface io
    )
  => Ptr a
  -> OffSet
  -> [a]
  -> io ()
store _ _ [    ] = pure ()
store p i (x:xs) = poke p i x >> store p (i+1) xs

--------------------------------------------------------------------------------

pow2 :: Int -> Int
pow2 x =
  if x .&. (x - 1) == 0
  then x
  else 1 `shiftL` (b - z)
  where
    b = finiteBitSize     x
    z = countLeadingZeros x

wait :: Applicative f => t -> a -> f a
wait x y =
  pure $ x `seq` y

next :: ( Storable a ) => Ptr a -> OffSet -> Ptr a
next p o =
  p `plusPtr` ( 1 * o) `asTypeOf` p

prev :: ( Storable a ) => Ptr a -> OffSet -> Ptr a
prev p o =
  p `plusPtr` (-1 * o) `asTypeOf` p

--------------------------------------------------------------------------------

sorter
  ::
    ( Storable a
    , Ord a
    , ForeignMemoryInterface io
    )
  => Ptr a
  -> OffSet
  -> Length
  -> io ()
sorter p o n =
  (
    if 2 < n
    then
      sorter p o m >>= \ f ->
      sorter q o m >>= \ s ->
      f `wait` s
    else
      pure ()
  ) >>= \ _ ->
  merger p o n
  where
    m = n `shiftR`   1
    q = p `plusPtr` (m * o) `asTypeOf` p

merger
  ::
    ( Storable a
    , Ord a
    , ForeignMemoryInterface io
    )
  => Ptr a
  -> OffSet
  -> Length
  -> io ()
merger p o n =
  w p (prev l o) >>= \ _ ->
  if 2 < n
  then
    bitonic p o m >>= \ f ->
    bitonic q o m >>= \ s ->
    f `wait` s
  else
    pure ()
  where
    m = n `shiftR`   1
    q = p `plusPtr` (m * o) `asTypeOf` p
    l = p `plusPtr` (n * o) `asTypeOf` p
    w i j
      | i   <   q = comparator i j >> w (next i o) (prev j o)
      | otherwise = pure ()

comparator
  ::
    ( Storable a
    , Ord a
    , ForeignMemoryInterface io
    )
  => Ptr a
  -> Ptr a
  -> io ()
comparator p q =
  peek p 0           >>= \ i ->
  peek q 0           >>= \ j ->
  poke p 0 (min i j) >>= \ f ->
  poke q 0 (max i j) >>= \ s ->
  f `wait` s

bitonic
  ::
    ( Storable a
    , Ord a
    , ForeignMemoryInterface io
    )
  => Ptr a
  -> OffSet
  -> Length
  -> io ()
bitonic p o n =
  cleaner p o n >>= \ _ ->
  if 2 < n
  then
    bitonic p o m >>= \ f ->
    bitonic q o m >>= \ s ->
    f `wait` s
  else
    pure ()
  where
    m = n `shiftR`   1
    q = p `plusPtr` (m * o) `asTypeOf` p

cleaner
  ::
    ( Storable a
    , Ord a
    , ForeignMemoryInterface io
    )
  => Ptr a
  -> OffSet
  -> Length
  -> io ()
cleaner p o n =
  w p q
  where
    m = n `shiftR`   1
    q = p `plusPtr` (m * o) `asTypeOf` p
    w i j
      | i   <   q = comparator i j >> w (next i o) (next j o)
      | otherwise = pure ()

Main.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
#!/usr/bin/env stack
{- stack
   --resolver lts-12.0
   --install-ghc
   script
   --ghc-options -Werror
   --ghc-options -Wall
   --
-}

{-# LANGUAGE Trustworthy #-}

--------------------------------------------------------------------------------

module Main (main) where

--------------------------------------------------------------------------------

import           System.IO.Unsafe
  ( unsafePerformIO
  )

import           Data.Bitonic
  ( SortableTrust
  , sort
  )

--------------------------------------------------------------------------------

-- In case you need the sorting algorithm to produce no IO effects, you will
-- have to create your own local version by implementing the `SortableTrust`
-- alias type with `unsafePerformIO`.

trust :: SortableTrust a
trust = unsafePerformIO . sort

--------------------------------------------------------------------------------

main :: IO ()
main =
  do
    putStrLn $ "# Bitonic sort"
    putStrLn $ "> xs (initial): " ++ (show  xs)
    sort xs >>= putStrLn . ("> ys (effects): " ++) . show
    putStrLn $ "> zs (trusted): " ++ (show $ trust xs)
      where
        xs = reverse [ 0 .. 15 ] :: [ Word ]

Code Output:

user@personal:~/../bitonic$ ./Main.hs
# Bitonic sort
> xs (initial): [15,14,13,12,11,10,9,8,7,6,5,4,3,2,1,0]
> ys (effects): [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
> zs (trusted): [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
user@personal:~/../bitonic$ 

References: