@@ -1,4 +1,6 @@
1+{-# LANGUAGE StrictData #-}
12{-# LANGUAGE TypeFamilyDependencies #-}
3+{-# LANGUAGE ConstraintKinds #-}
24{-# LANGUAGE AllowAmbiguousTypes #-}
35{-# LANGUAGE DataKinds #-}
46{-# LANGUAGE FlexibleContexts #-}
@@ -28,7 +30,7 @@
2830-- motivation behind the library, the underlying theory, and implementation details.
2931--
3032-- This module offers many of the combinators mentioned in the work of
31−-- Macedo (2012) and Oliveira (2012).
33+-- Macedo (2012) and Oliveira (2012).
3234--
3335-- This is an Internal module and it is no supposed to be imported.
3436--
@@ -41,17 +43,26 @@ module LAoP.Matrix.Internal
4143 --
4244 -- There exists two type families that make it easier to write
4345 -- matrix dimensions: 'FromNat' and 'Count'. This approach
44− -- leads to a very straightforward implementation
45− -- of LAoP combinators.
46+ -- leads to a very straightforward implementation
47+ -- of LAoP combinators.
4648
4749 -- * Type safe matrix representation
4850 Matrix (..),
4951
52+ -- * Constraint type aliases
53+ Countable,
54+ CountableDims,
55+ CountableN,
56+ CountableDimsN,
57+ FL,
58+ FLN,
59+ Liftable,
60+ Trivial,
61+
5062 -- * Primitives
51− empty,
5263 one,
53− junc,
54− split,
64+ join,
65+ fork,
5566
5667 -- * Auxiliary type families
5768 FromNat,
@@ -64,6 +75,7 @@ module LAoP.Matrix.Internal
6475 toLists,
6576 toList,
6677 matrixBuilder,
78+ matrixBuilder',
6779 row,
6880 col,
6981 zeros,
@@ -74,28 +86,38 @@ module LAoP.Matrix.Internal
7486 -- * Misc
7587 -- ** Get dimensions
7688 columns,
89+ columns',
7790 rows,
91+ rows',
7892
7993 -- ** Matrix Transposition
8094 tr,
8195
96+ -- ** Scalar multiplication/division of matrices
97+ (.|),
98+ (./),
99+
82100 -- ** Selective operator
83− select,
101+ select,
102+ branch,
84103
85104 -- ** McCarthy's Conditional
86105 cond,
87106
88107 -- ** Matrix "abiding"
89− abideJS,
90− abideSJ,
108+ abideJF,
109+ abideFJ,
110+
111+ -- ** Zip matrices
112+ zipWithM,
91113
92114 -- * Biproduct approach
93− -- ** Split
115+ -- ** Fork
94116 (===),
95117 -- *** Projections
96118 p1,
97119 p2,
98− -- ** Junc
120+ -- ** Join
99121 (|||),
100122 -- *** Injections
101123 i1,
@@ -108,12 +130,13 @@ module LAoP.Matrix.Internal
108130
109131 -- | Note that given the restrictions imposed it is not possible to
110132 -- implement the standard type classes present in standard Haskell.
133+
111134 -- *** Matrix pairing projections
112− kp1,
113− kp2,
135+ fstM,
136+ sndM,
114137
115138 -- *** Matrix pairing
116− khatri,
139+ kr,
117140
118141 -- * Matrix composition and lifting
119142
@@ -121,10 +144,10 @@ module LAoP.Matrix.Internal
121144
122145 -- | Note that given the restrictions imposed it is not possible to
123146 -- implement the standard type classes present in standard Haskell.
124− identity,
147+ iden,
125148 comp,
126− fromF,
127149 fromF',
150+ fromF,
128151
129152 -- * Matrix printing
130153 pretty,
@@ -134,6 +157,9 @@ module LAoP.Matrix.Internal
134157 toBool,
135158 fromBool,
136159 compRel,
160+ divR,
161+ divL,
162+ divS,
137163 fromFRel,
138164 fromFRel',
139165 toRel,
@@ -148,21 +174,22 @@ import LAoP.Utils.Internal
148174import Data.Bool
149175import Data.Kind
150176import Data.List
177+import Data.Maybe
151178import Data.Proxy
179+import Data.Typeable
152180import Data.Void
153181import GHC.TypeLits
154182import Data.Type.Equality
155183import GHC.Generics
156184import Control.DeepSeq
157−import Control.Category
158−import Prelude hiding ((.))
185+import Prelude hiding (id, (.))
186+import qualified Prelude (id, (.))
159187
160188-- | LAoP (Linear Algebra of Programming) Inductive Matrix definition.
161189data Matrix e cols rows where
162− Empty :: Matrix e Void Void
163190 One :: e -> Matrix e () ()
164− Junc :: Matrix e a rows -> Matrix e b rows -> Matrix e (Either a b) rows
165− Split :: Matrix e cols a -> Matrix e cols b -> Matrix e cols (Either a b)
191+ Join :: Matrix e a rows -> Matrix e b rows -> Matrix e (Either a b) rows
192+ Fork :: Matrix e cols a -> Matrix e cols b -> Matrix e cols (Either a b)
166193
167194deriving instance (Show e) => Show (Matrix e cols rows)
168195
@@ -172,221 +199,214 @@ deriving instance (Show e) => Show (Matrix e cols rows)
172199-- 'Generic' instance.
173200type family Count (d :: Type) :: Nat where
174201 Count (Natural n m) = (m - n) + 1
175− Count (Either a b) = (+) (Count a) (Count b)
176− Count (a, b) = (*) (Count a) (Count b)
177− Count (a -> b) = (^) (Count b) (Count a)
202+ Count (List a) = (^) 2 (Count a)
203+ Count (Either a b) = (+) (Count a) (Count b)
204+ Count (a, b) = (*) (Count a) (Count b)
205+ Count (a -> b) = (^) (Count b) (Count a)
178206 -- Generics
179− Count (M1 _ _ f p) = Count (f p)
180− Count (K1 _ _ _) = 1
181− Count (V1 _) = 0
182− Count (U1 _) = 1
207+ Count (M1 _ _ f p) = Count (f p)
208+ Count (K1 _ _ _) = 1
209+ Count (V1 _) = 0
210+ Count (U1 _) = 1
183211 Count ((:*:) a b p) = Count (a p) * Count (b p)
184212 Count ((:+:) a b p) = Count (a p) + Count (b p)
185− Count d = Count (Rep d R)
213+ Count d = Count (Rep d R)
186214
187215-- | Type family that computes of a given type dimension from a given natural
188216--
189217-- Thanks to Li-Yao Xia this type family is super fast.
190218type family FromNat (n :: Nat) :: Type where
191− FromNat 0 = Void
192219 FromNat 1 = ()
193220 FromNat n = FromNat' (Mod n 2 == 0) (FromNat (Div n 2))
194221
195222type family FromNat' (b :: Bool) (m :: Type) :: Type where
196− FromNat' 'True m = Either m m
223+ FromNat' 'True m = Either m m
197224 FromNat' 'False m = Either () (Either m m)
198225
199226-- | Type family that normalizes the representation of a given data
200227-- structure
201228type family Normalize (d :: Type) :: Type where
202− Normalize d = FromNat (Count d)
203−
204−-- | It isn't possible to implement the 'id' function so it's
205−-- implementation is 'undefined'. However 'comp' can be and this partial
206−-- class implementation exists just to make the code more readable.
207−--
208−-- Please use 'identity' instead.
229+ Normalize (Either a b) = Either (Normalize a) (Normalize b)
230+ Normalize d = FromNat (Count d)
231+
232+-- | Constraint type synonyms to keep the type signatures less convoluted
233+type Countable a = KnownNat (Count a)
234+type CountableN a = KnownNat (Count (Normalize a))
235+type CountableDims a b = (Countable a, Countable b)
236+type CountableDimsN a b = (CountableN a, CountableN b)
237+type FL a b = FromLists a b
238+type FLN a b = FromLists (Normalize a) (Normalize b)
239+type Liftable e a b = (Bounded a, Bounded b, Enum a, Enum b, Eq b, Num e, Ord e)
240+type Trivial a = FromNat (Count a) ~ a
241+
242+-- | It is possible to implement a constrained version of the category type
243+-- class.
209244instance (Num e) => Category (Matrix e) where
210− id = undefined
211− (.) = comp
245+ type Object (Matrix e) a = (FL a a, Countable a)
246+ id = iden
247+ (.) = comp
212248
213249instance NFData e => NFData (Matrix e cols rows) where
214− rnf Empty = ()
215− rnf (One e) = rnf e
216− rnf (Junc a b) = rnf a `seq` rnf b
217− rnf (Split a b) = rnf a `seq` rnf b
250+ rnf (One e) = rnf e
251+ rnf (Join a b) = rnf a `seq` rnf b
252+ rnf (Fork a b) = rnf a `seq` rnf b
218253
219254instance Eq e => Eq (Matrix e cols rows) where
220− Empty == Empty = True
221− (One a) == (One b) = a == b
222− (Junc a b) == (Junc c d) = a == c && b == d
223− (Split a b) == (Split c d) = a == c && b == d
224− x@(Split _ _) == y@(Junc _ _) = x == abideJS y
225− x@(Junc _ _) == y@(Split _ _) = abideJS x == y
255+ (One a) == (One b) = a == b
256+ (Join a b) == (Join c d) = a == c && b == d
257+ (Fork a b) == (Fork c d) = a == c && b == d
258+ x@(Fork _ _) == y@(Join _ _) = x == abideJF y
259+ x@(Join _ _) == y@(Fork _ _) = abideJF x == y
226260
227261instance Num e => Num (Matrix e cols rows) where
262+ a + b = zipWithM (+) a b
228263
229− Empty + Empty = Empty
230− (One a) + (One b) = One (a + b)
231− (Junc a b) + (Junc c d) = Junc (a + c) (b + d)
232− (Split a b) + (Split c d) = Split (a + c) (b + d)
233− x@(Split _ _) + y@(Junc _ _) = x + abideJS y
234− x@(Junc _ _) + y@(Split _ _) = abideJS x + y
235−
236− Empty - Empty = Empty
237− (One a) - (One b) = One (a - b)
238− (Junc a b) - (Junc c d) = Junc (a - c) (b - d)
239− (Split a b) - (Split c d) = Split (a - c) (b - d)
240− x@(Split _ _) - y@(Junc _ _) = x - abideJS y
241− x@(Junc _ _) - y@(Split _ _) = abideJS x - y
242−
243− Empty * Empty = Empty
244− (One a) * (One b) = One (a * b)
245− (Junc a b) * (Junc c d) = Junc (a * c) (b * d)
246− (Split a b) * (Split c d) = Split (a * c) (b * d)
247− x@(Split _ _) * y@(Junc _ _) = x * abideJS y
248− x@(Junc _ _) * y@(Split _ _) = abideJS x * y
249−
250− abs Empty = Empty
251− abs (One a) = One (abs a)
252− abs (Junc a b) = Junc (abs a) (abs b)
253− abs (Split a b) = Split (abs a) (abs b)
254−
255− signum Empty = Empty
256− signum (One a) = One (signum a)
257− signum (Junc a b) = Junc (signum a) (signum b)
258− signum (Split a b) = Split (signum a) (signum b)
264+ a - b = zipWithM (-) a b
265+
266+ a * b = zipWithM (*) a b
267+
268+ abs (One a) = One (abs a)
269+ abs (Join a b) = Join (abs a) (abs b)
270+ abs (Fork a b) = Fork (abs a) (abs b)
271+
272+ signum (One a) = One (signum a)
273+ signum (Join a b) = Join (signum a) (signum b)
274+ signum (Fork a b) = Fork (signum a) (signum b)
259275
260276instance Ord e => Ord (Matrix e cols rows) where
261− Empty <= Empty = True
262− (One a) <= (One b) = a <= b
263− (Junc a b) <= (Junc c d) = (a <= c) && (b <= d)
264− (Split a b) <= (Split c d) = (a <= c) && (b <= d)
265− x@(Split _ _) <= y@(Junc _ _) = x <= abideJS y
266− x@(Junc _ _) <= y@(Split _ _) = abideJS x <= y
277+ (One a) <= (One b) = a <= b
278+ (Join a b) <= (Join c d) = (a <= c) && (b <= d)
279+ (Fork a b) <= (Fork c d) = (a <= c) && (b <= d)
280+ x@(Fork _ _) <= y@(Join _ _) = x <= abideJF y
281+ x@(Join _ _) <= y@(Fork _ _) = abideJF x <= y
267282
268283-- Primitives
269284
270−-- | Empty matrix constructor
271−empty :: Matrix e Void Void
272−empty = Empty
273−
274285-- | Unit matrix constructor
275286one :: e -> Matrix e () ()
276287one = One
277288
278−-- | Matrix 'Junc' constructor
279−junc :: Matrix e a rows -> Matrix e b rows -> Matrix e (Either a b) rows
280−junc = Junc
289+-- | Matrix 'Join' constructor
290+join :: Matrix e a rows -> Matrix e b rows -> Matrix e (Either a b) rows
291+join = Join
281292
282293infixl 3 |||
283294
284−-- | Matrix 'Junc' constructor
295+-- | Matrix 'Join' constructor
285296(|||) :: Matrix e a rows -> Matrix e b rows -> Matrix e (Either a b) rows
286−(|||) = Junc
297+(|||) = Join
287298
288−-- | Matrix 'Split' constructor
289−split :: Matrix e cols a -> Matrix e cols b -> Matrix e cols (Either a b)
290−split = Split
299+-- | Matrix 'Fork' constructor
300+fork :: Matrix e cols a -> Matrix e cols b -> Matrix e cols (Either a b)
301+fork = Fork
291302
292303infixl 2 ===
293304
294−-- | Matrix 'Split' constructor
305+-- | Matrix 'Fork' constructor
295306(===) :: Matrix e cols a -> Matrix e cols b -> Matrix e cols (Either a b)
296−(===) = Split
307+(===) = Fork
297308
298309-- Construction
299310
300311-- | Type class for defining the 'fromList' conversion function.
301312--
302313-- Given that it is not possible to branch on types at the term level type
303−-- classes are needed bery much like an inductive definition but on types.
304−class FromLists e cols rows where
314+-- classes are needed very much like an inductive definition but on types.
315+class FromLists cols rows where
305316 -- | Build a matrix out of a list of list of elements. Throws a runtime
306317 -- error if the dimensions do not match.
307318 fromLists :: [[e]] -> Matrix e cols rows
308319
309−instance FromLists e Void Void where
310− fromLists [] = Empty
311− fromLists _ = error "Wrong dimensions"
312−
313−instance {-# OVERLAPPING #-} FromLists e () () where
320+instance FromLists () () where
314321 fromLists [[e]] = One e
315322 fromLists _ = error "Wrong dimensions"
316323
317−instance {-# OVERLAPPING #-} (FromLists e cols ()) => FromLists e (Either () cols) () where
318− fromLists [h : t] = Junc (One h) (fromLists [t])
324+instance (FromLists cols ()) => FromLists (Either () cols) () where
325+ fromLists [h : t] = Join (One h) (fromLists [t])
319326 fromLists _ = error "Wrong dimensions"
320327
321−instance {-# OVERLAPPABLE #-} (FromLists e a (), FromLists e b (), KnownNat (Count a)) => FromLists e (Either a b) () where
322− fromLists [l] =
328+instance {-# OVERLAPPABLE #-}
329+ (FromLists a (), FromLists b (), Countable a) => FromLists (Either a b) () where
330+ fromLists [l] =
323331 let rowsA = fromInteger (natVal (Proxy :: Proxy (Count a)))
324− in Junc (fromLists [take rowsA l]) (fromLists [drop rowsA l])
332+ in Join (fromLists [take rowsA l]) (fromLists [drop rowsA l])
325333 fromLists _ = error "Wrong dimensions"
326334
327−instance {-# OVERLAPPING #-} (FromLists e () rows) => FromLists e () (Either () rows) where
328− fromLists ([h] : t) = Split (One h) (fromLists t)
335+instance (FromLists () rows) => FromLists () (Either () rows) where
336+ fromLists ([h] : t) = Fork (One h) (fromLists t)
329337 fromLists _ = error "Wrong dimensions"
330338
331−instance {-# OVERLAPPABLE #-} (FromLists e () a, FromLists e () b, KnownNat (Count a)) => FromLists e () (Either a b) where
332− fromLists l@([_] : _) =
339+instance {-# OVERLAPPABLE #-}
340+ (FromLists () a, FromLists () b, Countable a) => FromLists () (Either a b) where
341+ fromLists l@([_] : _) =
333342 let rowsA = fromInteger (natVal (Proxy :: Proxy (Count a)))
334− in Split (fromLists (take rowsA l)) (fromLists (drop rowsA l))
343+ in Fork (fromLists (take rowsA l)) (fromLists (drop rowsA l))
335344 fromLists _ = error "Wrong dimensions"
336345
337−instance {-# OVERLAPPABLE #-} (FromLists e (Either a b) c, FromLists e (Either a b) d, KnownNat (Count c)) => FromLists e (Either a b) (Either c d) where
346+instance (FromLists (Either a b) c, FromLists (Either a b) d, Countable c)
347+ => FromLists (Either a b) (Either c d) where
338348 fromLists l@(h : t) =
339349 let lh = length h
340350 rowsC = fromInteger (natVal (Proxy :: Proxy (Count c)))
341− condition = all (== lh) (map length t)
351+ condition = all ((== lh) . length) t
342352 in if lh > 0 && condition
343− then Split (fromLists (take rowsC l)) (fromLists (drop rowsC l))
353+ then Fork (fromLists (take rowsC l)) (fromLists (drop rowsC l))
344354 else error "Not all rows have the same length"
345355
346356-- | Matrix builder function. Constructs a matrix provided with
347−-- a construction function.
348−matrixBuilder ::
357+-- a construction function that operates with indices.
358+matrixBuilder' ::
349359 forall e cols rows.
350− ( FromLists e cols rows,
351− KnownNat (Count cols),
352− KnownNat (Count rows)
353− ) =>
354− ((Int, Int) -> e) ->
355− Matrix e cols rows
356−matrixBuilder f =
360+ ( FL cols rows,
361+ CountableDims cols rows
362+ ) => ((Int, Int) -> e) -> Matrix e cols rows
363+matrixBuilder' f =
357364 let c = fromInteger $ natVal (Proxy :: Proxy (Count cols))
358365 r = fromInteger $ natVal (Proxy :: Proxy (Count rows))
359366 positions = [(a, b) | a <- [0 .. (r - 1)], b <- [0 .. (c - 1)]]
360367 in fromLists . map (map f) . groupBy (\(x, _) (w, _) -> x == w) $ positions
361368
369+-- | Matrix builder function. Constructs a matrix provided with
370+-- a construction function that operates with arbitrary types.
371+matrixBuilder ::
372+ forall e a b.
373+ ( FLN a b,
374+ Enum a,
375+ Enum b,
376+ Bounded a,
377+ Bounded b,
378+ Eq a,
379+ Countable b
380+ ) => ((a, b) -> e) -> Matrix e (Normalize a) (Normalize b)
381+matrixBuilder f =
382+ let r = fromInteger $ natVal (Proxy :: Proxy (Count b))
383+ positions = [(a, b) | a <- [minBound .. maxBound], b <- [minBound .. maxBound]]
384+ in fromLists . map (map f) . transpose . buildList r $ positions
385+ where
386+ buildList _ [] = []
387+ buildList r l = take r l : buildList r (drop r l)
388+
362389-- | Constructs a column vector matrix
363−col :: (FromLists e () rows) => [e] -> Matrix e () rows
390+col :: (FL () rows) => [e] -> Matrix e () rows
364391col = fromLists . map (: [])
365392
366393-- | Constructs a row vector matrix
367−row :: (FromLists e cols ()) => [e] -> Matrix e cols ()
394+row :: (FL cols ()) => [e] -> Matrix e cols ()
368395row = fromLists . (: [])
369396
370397-- | Lifts functions to matrices with arbitrary dimensions.
371398--
372399-- NOTE: Be careful to not ask for a matrix bigger than the cardinality of
373400-- types @a@ or @b@ allows.
374−fromF ::
401+fromF' ::
375402 forall a b cols rows e.
376− ( Bounded a,
377− Bounded b,
378− Enum a,
379− Enum b,
380− Eq b,
381− Num e,
382− Ord e,
383− KnownNat (Count cols),
384− KnownNat (Count rows),
385− FromLists e rows cols
403+ ( Liftable e a b,
404+ CountableDims cols rows,
405+ FL rows cols
386406 ) =>
387407 (a -> b) ->
388408 Matrix e cols rows
389−fromF f =
409+fromF' f =
390410 let minA = minBound @a
391411 maxA = maxBound @a
392412 minB = minBound @b
@@ -396,8 +416,8 @@ fromF f =
396416 elementsA = take ccols [minA .. maxA]
397417 elementsB = take rrows [minB .. maxB]
398418 combinations = (,) <$> elementsA <*> elementsB
399− combAp = map snd . sort . map (\(a, b) -> if f a == b
400− then ((fromEnum a, fromEnum b), 1)
419+ combAp = map snd . sort . map (\(a, b) -> if f a == b
420+ then ((fromEnum a, fromEnum b), 1)
401421 else ((fromEnum a, fromEnum b), 0)) $ combinations
402422 mList = buildList combAp rrows
403423 in tr $ fromLists mList
@@ -407,48 +427,23 @@ fromF f =
407427
408428-- | Lifts functions to matrices with dimensions matching @a@ and @b@
409429-- cardinality's.
410−fromF' ::
430+fromF ::
411431 forall a b e.
412− ( Bounded a,
413− Bounded b,
414− Enum a,
415− Enum b,
416− Eq b,
417− Num e,
418− Ord e,
419− KnownNat (Count (Normalize a)),
420− KnownNat (Count (Normalize b)),
421− FromLists e (Normalize b) (Normalize a)
432+ ( Liftable e a b,
433+ CountableDimsN a b,
434+ FLN b a
422435 ) =>
423436 (a -> b) ->
424437 Matrix e (Normalize a) (Normalize b)
425−fromF' f =
426− let minA = minBound @a
427− maxA = maxBound @a
428− minB = minBound @b
429− maxB = maxBound @b
430− ccols = fromInteger $ natVal (Proxy :: Proxy (Count (Normalize a)))
431− rrows = fromInteger $ natVal (Proxy :: Proxy (Count (Normalize b)))
432− elementsA = take ccols [minA .. maxA]
433− elementsB = take rrows [minB .. maxB]
434− combinations = (,) <$> elementsA <*> elementsB
435− combAp = map snd . sort . map (\(a, b) -> if f a == b
436− then ((fromEnum a, fromEnum b), 1)
437− else ((fromEnum a, fromEnum b), 0)) $ combinations
438− mList = buildList combAp rrows
439− in tr $ fromLists mList
440− where
441− buildList [] _ = []
442− buildList l r = take r l : buildList (drop r l) r
438+fromF = fromF'
443439
444440-- Conversion
445441
446442-- | Converts a matrix to a list of lists of elements.
447443toLists :: Matrix e cols rows -> [[e]]
448−toLists Empty = []
449444toLists (One e) = [[e]]
450−toLists (Split l r) = toLists l ++ toLists r
451−toLists (Junc l r) = zipWith (++) (toLists l) (toLists r)
445+toLists (Fork l r) = toLists l ++ toLists r
446+toLists (Join l r) = zipWith (++) (toLists l) (toLists r)
452447
453448-- | Converts a matrix to a list of elements.
454449toList :: Matrix e cols rows -> [e]
@@ -457,37 +452,38 @@ toList = concat . toLists
457452-- Zeros Matrix
458453
459454-- | The zero matrix. A matrix wholly filled with zeros.
460−zeros :: (Num e, FromLists e cols rows, KnownNat (Count cols), KnownNat (Count rows)) => Matrix e cols rows
461−zeros = matrixBuilder (const 0)
455+zeros :: (Num e, FL cols rows, CountableDims cols rows) => Matrix e cols rows
456+zeros = matrixBuilder' (const 0)
462457
463458-- Ones Matrix
464459
465460-- | The ones matrix. A matrix wholly filled with ones.
466461--
467462-- Also known as T (Top) matrix.
468−ones :: (Num e, FromLists e cols rows, KnownNat (Count cols), KnownNat (Count rows)) => Matrix e cols rows
469−ones = matrixBuilder (const 1)
463+ones :: (Num e, FL cols rows, CountableDims cols rows) => Matrix e cols rows
464+ones = matrixBuilder' (const 1)
470465
471466-- Const Matrix
472467
473468-- | The constant matrix constructor. A matrix wholly filled with a given
474469-- value.
475−constant :: (Num e, FromLists e cols rows, KnownNat (Count cols), KnownNat (Count rows)) => e -> Matrix e cols rows
476−constant e = matrixBuilder (const e)
470+constant :: (Num e, FL cols rows, CountableDims cols rows) => e -> Matrix e cols rows
471+constant e = matrixBuilder' (const e)
477472
478473-- Bang Matrix
479474
480475-- | The T (Top) row vector matrix.
481−bang :: forall e cols. (Num e, Enum e, FromLists e cols (), KnownNat (Count cols)) => Matrix e cols ()
476+bang :: forall e cols. (Num e, Enum e, FL cols (), Countable cols) => Matrix e cols ()
482477bang =
483478 let c = fromInteger $ natVal (Proxy :: Proxy (Count cols))
484479 in fromLists [take c [1, 1 ..]]
485480
486−-- Identity Matrix
481+-- iden Matrix
487482
488−-- | Identity matrix.
489−identity :: (Num e, FromLists e cols cols, KnownNat (Count cols)) => Matrix e cols cols
490−identity = matrixBuilder (bool 0 1 . uncurry (==))
483+-- | iden matrix.
484+iden :: forall e cols . (Num e, FL cols cols, Countable cols) => Matrix e cols cols
485+iden = matrixBuilder' (bool 0 1 . uncurry (==))
486+{-# NOINLINE iden #-}
491487
492488-- Matrix composition (MMM)
493489
@@ -496,60 +492,90 @@ identity = matrixBuilder (bool 0 1 . uncurry (==))
496492-- This definition takes advantage of divide-and-conquer and fusion laws
497493-- from LAoP.
498494comp :: (Num e) => Matrix e cr rows -> Matrix e cols cr -> Matrix e cols rows
499−comp Empty Empty = Empty
500−comp (One a) (One b) = One (a * b)
501−comp (Junc a b) (Split c d) = comp a c + comp b d -- Divide-and-conquer law
502−comp (Split a b) c = Split (comp a c) (comp b c) -- Split fusion law
503−comp c (Junc a b) = Junc (comp c a) (comp c b) -- Junc fusion law
495+comp (One a) (One b) = One (a * b)
496+comp (Join a b) (Fork c d) = comp a c + comp b d -- Divide-and-conquer law
497+comp (Fork a b) c = Fork (comp a c) (comp b c) -- Fork fusion law
498+comp c (Join a b) = Join (comp c a) (comp c b) -- Join fusion law
499+{-# NOINLINE comp #-}
500+{-# RULES
501+ "comp/iden1" forall m. comp m iden = m ;
502+ "comp/iden2" forall m. comp iden m = m
503+#-}
504+
505+-- Scalar multiplication of matrices
506+
507+infixl 7 .|
508+-- | Scalar multiplication of matrices.
509+(.|) :: Num e => e -> Matrix e cols rows -> Matrix e cols rows
510+(.|) e (One a) = One (e * a)
511+(.|) e (Join a b) = Join (e .| a) (e .| b)
512+(.|) e (Fork a b) = Fork (e .| a) (e .| b)
513+
514+-- Scalar division of matrices
515+
516+infixl 7 ./
517+-- | Scalar multiplication of matrices.
518+(./) :: Fractional e => Matrix e cols rows -> e -> Matrix e cols rows
519+(./) (One a) e = One (a / e)
520+(./) (Join a b) e = Join (a ./ e) (b ./ e)
521+(./) (Fork a b) e = Fork (a ./ e) (b ./ e)
504522
505523-- Projections
506524
507525-- | Biproduct first component projection
508−p1 :: forall e m n. (Num e, KnownNat (Count n), KnownNat (Count m), FromLists e n m, FromLists e m m) => Matrix e (Either m n) m
509−p1 =
510− let iden = identity :: Matrix e m m
511− zero = zeros :: Matrix e n m
512− in junc iden zero
526+p1 :: (Num e, CountableDims n m, FL n m, FL m m) => Matrix e (Either m n) m
527+p1 = join id zeros
513528
514529-- | Biproduct second component projection
515−p2 :: forall e m n. (Num e, KnownNat (Count n), KnownNat (Count m), FromLists e m n, FromLists e n n) => Matrix e (Either m n) n
516−p2 =
517− let iden = identity :: Matrix e n n
518− zero = zeros :: Matrix e m n
519− in junc zero iden
530+p2 :: (Num e, CountableDims n m, FL m n, FL n n) => Matrix e (Either m n) n
531+p2 = join zeros id
520532
521533-- Injections
522534
523535-- | Biproduct first component injection
524−i1 :: (Num e, KnownNat (Count n), KnownNat (Count m), FromLists e n m, FromLists e m m) => Matrix e m (Either m n)
536+i1 :: (Num e, CountableDims n m, FL n m, FL m m) => Matrix e m (Either m n)
525537i1 = tr p1
526538
527539-- | Biproduct second component injection
528−i2 :: (Num e, KnownNat (Count n), KnownNat (Count m), FromLists e m n, FromLists e n n) => Matrix e n (Either m n)
540+i2 :: (Num e, CountableDims n m, FL m n, FL n n) => Matrix e n (Either m n)
529541i2 = tr p2
530542
531543-- Dimensions
532544
533545-- | Obtain the number of rows.
534546--
535−-- NOTE: The 'KnownNat' constaint is needed in order to obtain the
536−-- dimensions in constant time.
537−--
538−-- TODO: A 'rows' function that does not need the 'KnownNat' constraint in
539−-- exchange for performance.
540−rows :: forall e cols rows. (KnownNat (Count rows)) => Matrix e cols rows -> Int
547+-- NOTE: The 'KnownNat' constraint is needed in order to obtain the
548+-- dimensions in constant time. For a version that doesn't require the
549+-- constraint see 'rows''.
550+rows :: forall e cols rows. (Countable rows) => Matrix e cols rows -> Int
541551rows _ = fromInteger $ natVal (Proxy :: Proxy (Count rows))
542552
553+-- | Obtain the number of rows in an inefficient manner, but without any
554+-- constraints.
555+--
556+-- For a more efficient version see 'rows'.
557+rows' :: Matrix e cols rows -> Int
558+rows' (One _) = 1
559+rows' (Join lhs _) = rows' lhs
560+rows' (Fork top bottom) = rows' top + rows' bottom
561+
543562-- | Obtain the number of columns.
544−--
545−-- NOTE: The 'KnownNat' constaint is needed in order to obtain the
546−-- dimensions in constant time.
547563--
548−-- TODO: A 'columns' function that does not need the 'KnownNat' constraint in
549−-- exchange for performance.
550−columns :: forall e cols rows. (KnownNat (Count cols)) => Matrix e cols rows -> Int
564+-- NOTE: The 'KnownNat' constraint is needed in order to obtain the
565+-- dimensions in constant time. For a version that doesn't require the
566+-- constraint see 'columns''.
567+columns :: forall e cols rows. (Countable cols) => Matrix e cols rows -> Int
551568columns _ = fromInteger $ natVal (Proxy :: Proxy (Count cols))
552569
570+-- | Obtain the number of columns in an inefficient manner, but without any
571+-- constraints.
572+--
573+-- For a more efficient version see 'columns'.
574+columns' :: Matrix e cols rows -> Int
575+columns' (One _) = 1
576+columns' (Join lhs rhs) = columns' lhs + columns' rhs
577+columns' (Fork top _) = columns' top
578+
553579-- Coproduct Bifunctor
554580
555581infixl 5 -|-
@@ -558,157 +584,172 @@ infixl 5 -|-
558584(-|-) ::
559585 forall e n k m j.
560586 ( Num e,
561− KnownNat (Count j),
562− KnownNat (Count k),
563− FromLists e k k,
564− FromLists e j k,
565− FromLists e k j,
566− FromLists e j j
587+ CountableDims j k,
588+ FL k k,
589+ FL j k,
590+ FL k j,
591+ FL j j
567592 ) =>
568593 Matrix e n k ->
569594 Matrix e m j ->
570595 Matrix e (Either n m) (Either k j)
571−(-|-) a b = Junc (i1 . a) (i2 . b)
596+(-|-) a b = Join (i1 . a) (i2 . b)
572597
573598-- Khatri Rao Product and projections
574599
575600-- | Khatri Rao product first component projection matrix.
576−kp1 ::
601+fstM ::
577602 forall e m k .
578603 ( Num e,
579− KnownNat (Count k),
580− FromLists e (FromNat (Count m * Count k)) m,
581− KnownNat (Count m),
582− KnownNat (Count (Normalize (m, k)))
604+ CountableDims k m,
605+ FL (Normalize (m, k)) m,
606+ CountableN (m, k)
583607 ) => Matrix e (Normalize (m, k)) m
584−kp1 = matrixBuilder f
608+fstM = matrixBuilder' f
585609 where
586610 offset = fromInteger (natVal (Proxy :: Proxy (Count k)))
587611 f (x, y)
588612 | y >= (x * offset) && y <= (x * offset + offset - 1) = 1
589− | otherwise = 0
613+ | otherwise = 0
590614
591615-- | Khatri Rao product second component projection matrix.
592−kp2 ::
616+sndM ::
593617 forall e m k .
594618 ( Num e,
595− KnownNat (Count k),
596− FromLists e (FromNat (Count m * Count k)) k,
597− KnownNat (Count m),
598− KnownNat (Count (Normalize (m, k)))
619+ CountableDims k m,
620+ FL (Normalize (m, k)) k,
621+ CountableN (m, k)
599622 ) => Matrix e (Normalize (m, k)) k
600−kp2 = matrixBuilder f
623+sndM = matrixBuilder' f
601624 where
602625 offset = fromInteger (natVal (Proxy :: Proxy (Count k)))
603626 f (x, y)
604627 | x == y || mod (y - x) offset == 0 = 1
605− | otherwise = 0
628+ | otherwise = 0
606629
607630-- | Khatri Rao Matrix product also known as matrix pairing.
608631--
609632-- NOTE: That this is not a true categorical product, see for instance:
610−--
633+--
611634-- @
612−-- | kp1 . khatri a b == a
613−-- khatri a b ==> |
614−-- | kp2 . khatri a b == b
635+-- | fstM . kr a b == a
636+-- kr a b ==> |
637+-- | sndM . kr a b == b
615638-- @
616639--
617640-- __Emphasis__ on the implication symbol.
618−khatri ::
619− forall e cols a b.
641+kr ::
642+ forall e cols a b.
620643 ( Num e,
621− KnownNat (Count a),
622− KnownNat (Count b),
623− KnownNat (Count (Normalize (a, b))),
624− FromLists e (Normalize (a, b)) a,
625− FromLists e (Normalize (a, b)) b
644+ CountableDims a b,
645+ CountableN (a, b),
646+ FL (Normalize (a, b)) a,
647+ FL (Normalize (a, b)) b
626648 ) => Matrix e cols a -> Matrix e cols b -> Matrix e cols (Normalize (a, b))
627−khatri a b =
628− let kp1' = kp1 @e @a @b
629− kp2' = kp2 @e @a @b
630− in (tr kp1') . a * (tr kp2') . b
649+kr a b =
650+ let fstM' = fstM @e @a @b
651+ sndM' = sndM @e @a @b
652+ in (tr fstM' . a) * (tr sndM' . b)
631653
632654-- Product Bifunctor (Kronecker)
633655
634656infixl 4 ><
635657
636658-- | Matrix product functor also known as kronecker product
637−(><) ::
638− forall e m p n q.
659+(><) ::
660+ forall e m p n q.
639661 ( Num e,
640− KnownNat (Count m),
641− KnownNat (Count n),
642− KnownNat (Count p),
643− KnownNat (Count q),
644− KnownNat (Count (Normalize (m, n))),
645− FromLists e (Normalize (m, n)) m,
646− FromLists e (Normalize (m, n)) n,
647− KnownNat (Count (Normalize (p, q))),
648− FromLists e (Normalize (p, q)) p,
649− FromLists e (Normalize (p, q)) q
650− )
662+ CountableDims m n,
663+ CountableDims p q,
664+ CountableDimsN (m, n) (p, q),
665+ FL (Normalize (m, n)) m,
666+ FL (Normalize (m, n)) n,
667+ FL (Normalize (p, q)) p,
668+ FL (Normalize (p, q)) q
669+ )
651670 => Matrix e m p -> Matrix e n q -> Matrix e (Normalize (m, n)) (Normalize (p, q))
652671(><) a b =
653− let kp1' = kp1 @e @m @n
654− kp2' = kp2 @e @m @n
655− in khatri (a . kp1') (b . kp2')
672+ let fstM' = fstM @e @m @n
673+ sndM' = sndM @e @m @n
674+ in kr (a . fstM') (b . sndM')
656675
657−-- Matrix abide Junc Split
676+-- Matrix abide Join Fork
658677
659−-- | Matrix "abiding" followin the 'Junc'-'Split' abide law.
660−--
678+-- | Matrix "abiding" following the 'Join'-'Fork' exchange law.
679+--
661680-- Law:
662681--
663682-- @
664−-- 'Junc' ('Split' a c) ('Split' b d) == 'Split' ('Junc' a b) ('Junc' c d)
683+-- 'Join' ('Fork' a c) ('Fork' b d) == 'Fork' ('Join' a b) ('Join' c d)
665684-- @
666−abideJS :: Matrix e cols rows -> Matrix e cols rows
667−abideJS (Junc (Split a c) (Split b d)) = Split (Junc (abideJS a) (abideJS b)) (Junc (abideJS c) (abideJS d)) -- Junc-Split abide law
668−abideJS Empty = Empty
669−abideJS (One e) = One e
670−abideJS (Junc a b) = Junc (abideJS a) (abideJS b)
671−abideJS (Split a b) = Split (abideJS a) (abideJS b)
685+abideJF :: Matrix e cols rows -> Matrix e cols rows
686+abideJF (Join (Fork a c) (Fork b d)) = Fork (Join (abideJF a) (abideJF b)) (Join (abideJF c) (abideJF d)) -- Join-Fork abide law
687+abideJF (One e) = One e
688+abideJF (Join a b) = Join (abideJF a) (abideJF b)
689+abideJF (Fork a b) = Fork (abideJF a) (abideJF b)
672690
673−-- Matrix abide Split Junc
691+-- Matrix abide Fork Join
674692
675−-- | Matrix "abiding" followin the 'Split'-'Junc' abide law.
676−--
693+-- | Matrix "abiding" followin the 'Fork'-'Join' abide law.
694+--
677695-- @
678−-- 'Split' ('Junc' a b) ('Junc' c d) == 'Junc' ('Split' a c) ('Split' b d)
696+-- 'Fork' ('Join' a b) ('Join' c d) == 'Join' ('Fork' a c) ('Fork' b d)
679697-- @
680−abideSJ :: Matrix e cols rows -> Matrix e cols rows
681−abideSJ (Split (Junc a b) (Junc c d)) = Junc (Split (abideSJ a) (abideSJ c)) (Split (abideSJ b) (abideSJ d)) -- Split-Junc abide law
682−abideSJ Empty = Empty
683−abideSJ (One e) = One e
684−abideSJ (Junc a b) = Junc (abideSJ a) (abideSJ b)
685−abideSJ (Split a b) = Split (abideSJ a) (abideSJ b)
698+abideFJ :: Matrix e cols rows -> Matrix e cols rows
699+abideFJ (Fork (Join a b) (Join c d)) = Join (Fork (abideFJ a) (abideFJ c)) (Fork (abideFJ b) (abideFJ d)) -- Fork-Join abide law
700+abideFJ (One e) = One e
701+abideFJ (Join a b) = Join (abideFJ a) (abideFJ b)
702+abideFJ (Fork a b) = Fork (abideFJ a) (abideFJ b)
686703
687704-- Matrix transposition
688705
689706-- | Matrix transposition.
690707tr :: Matrix e cols rows -> Matrix e rows cols
691−tr Empty = Empty
692−tr (One e) = One e
693−tr (Junc a b) = Split (tr a) (tr b)
694−tr (Split a b) = Junc (tr a) (tr b)
708+tr (One e) = One e
709+tr (Join a b) = Fork (tr a) (tr b)
710+tr (Fork a b) = Join (tr a) (tr b)
695711
696712-- Selective 'select' operator
697713
698714-- | Selective functors 'select' operator equivalent inspired by the
699715-- ArrowMonad solution presented in the paper.
700−select :: (Num e, FromLists e b b, KnownNat (Count b)) => Matrix e cols (Either a b) -> Matrix e a b -> Matrix e cols b
701−select m y = junc y identity . m
716+select :: (Num e, FL b b, Countable b) => Matrix e cols (Either a b) -> Matrix e a b -> Matrix e cols b
717+select (Fork a b) y = y . a + b -- Divide-and-conquer law
718+select (Join (Fork a c) (Fork b d)) y = join (y . a + c) (y . b + d) -- Pattern matching + DnC law
719+select m y = join y id . m
720+
721+branch ::
722+ ( Num e,
723+ CountableDims a b,
724+ CountableDims c (Either b c),
725+ FL c b,
726+ FL a b,
727+ FL a a,
728+ FL b b,
729+ FL c c,
730+ FL b a,
731+ FL b c,
732+ FL (Either b c) b,
733+ FL (Either b c) c
734+ )
735+ => Matrix e cols (Either a b) -> Matrix e a c -> Matrix e b c -> Matrix e cols c
736+branch x l r = f x `select` g l `select` r
737+ where
738+ f :: (Num e, Countable a, CountableDims b c, FL a b, FL c b, FL b b, FL b a, FL a a)
739+ => Matrix e cols (Either a b) -> Matrix e cols (Either a (Either b c))
740+ f m = fork (tr i1) (i1 . tr i2) . m
741+ g :: (Num e, CountableDims b c, FL b c, FL c c) => Matrix e a c -> Matrix e a (Either b c)
742+ g m = i2 . m
702743
703744-- McCarthy's Conditional
704745
705746-- | McCarthy's Conditional expresses probabilistic choice.
706747cond ::
707− ( cols ~ FromNat (Count cols),
708− KnownNat (Count cols),
709− FromLists e () cols,
710− FromLists e cols (),
711− FromLists e cols cols,
748+ ( Trivial cols,
749+ Countable cols,
750+ FL () cols,
751+ FL cols (),
752+ FL cols cols,
712753 Bounded a,
713754 Enum a,
714755 Num e,
@@ -716,14 +757,14 @@ cond ::
716757 )
717758 =>
718759 (a -> Bool) -> Matrix e cols rows -> Matrix e cols rows -> Matrix e cols rows
719−cond p f g = junc f g . grd p
720−
721−grd ::
722− ( q ~ FromNat (Count q),
723− KnownNat (Count q),
724− FromLists e () q,
725− FromLists e q (),
726− FromLists e q q,
760+cond p f g = join f g . grd p
761+
762+grd ::
763+ ( Trivial q,
764+ Countable q,
765+ FL () q,
766+ FL q (),
767+ FL q q,
727768 Bounded a,
728769 Enum a,
729770 Num e,
@@ -731,62 +772,88 @@ grd ::
731772 )
732773 =>
733774 (a -> Bool) -> Matrix e q (Either q q)
734−grd f = split (corr f) (corr (not . f))
735−
736−corr ::
737− forall e a q .
738− ( q ~ FromNat (Count q),
739− KnownNat (Count q),
740− FromLists e () q,
741− FromLists e q (),
742− FromLists e q q,
743− Bounded a,
744− Enum a,
745− Num e,
746− Ord e
747− )
775+grd f = fork (corr f) (corr (not . f))
776+
777+corr ::
778+ forall e a q .
779+ ( Trivial q,
780+ Countable q,
781+ FL () q,
782+ FL q (),
783+ FL q q,
784+ Liftable e a Bool
785+ )
748786 => (a -> Bool) -> Matrix e q q
749−corr p = let f = fromF p :: Matrix e q ()
750− in khatri f (identity :: Matrix e q q)
787+corr p = let f = fromF' p :: Matrix e q ()
788+ in kr f (id :: Matrix e q q)
751789
752790-- Pretty print
753791
754792prettyAux :: Show e => [[e]] -> [[e]] -> String
755793prettyAux [] _ = ""
756−prettyAux [[e]] m = "│ " ++ fill (show e) ++ " │\n"
794+prettyAux [[e]] m = "│ " ++ fill (show e) ++ " │\n"
757795 where
758796 v = fmap show m
759797 widest = maximum $ fmap length v
760798 fill str = replicate (widest - length str - 2) ' ' ++ str
761−prettyAux [h] m = "│ " ++ fill (unwords $ map show h) ++ " │\n"
799+prettyAux [h] m = "│ " ++ fill (unwords $ map show h) ++ " │\n"
762800 where
763− v = fmap show m
764− widest = maximum $ fmap length v
801+ v = fmap show m
802+ widest = maximum $ fmap length v
765803 fill str = replicate (widest - length str - 2) ' ' ++ str
766−prettyAux (h : t) l = "│ " ++ fill (unwords $ map show h) ++ " │\n" ++
804+prettyAux (h : t) l = "│ " ++ fill (unwords $ map show h) ++ " │\n" ++
767805 prettyAux t l
768806 where
769− v = fmap show l
770− widest = maximum $ fmap length v
807+ v = fmap show l
808+ widest = maximum $ fmap length v
771809 fill str = replicate (widest - length str - 2) ' ' ++ str
772810
773811-- | Matrix pretty printer
774−pretty :: (KnownNat (Count cols), Show e) => Matrix e cols rows -> String
775−pretty m = "┌ " ++ unwords (replicate (columns m) blank) ++ " ┐\n" ++
776− prettyAux (toLists m) (toLists m) ++
777− "└ " ++ unwords (replicate (columns m) blank) ++ " ┘"
778− where
779− v = fmap show (toList m)
780− widest = maximum $ fmap length v
812+pretty :: (CountableDims cols rows, Show e) => Matrix e cols rows -> String
813+pretty m = concat
814+ [ "┌ ", unwords (replicate (columns m) blank), " ┐\n"
815+ , unlines
816+ [ "│ " ++ unwords (fmap (\j -> fill $ show $ getElem i j m) [1..columns m]) ++ " │" | i <- [1..rows m] ]
817+ , "└ ", unwords (replicate (columns m) blank), " ┘"
818+ ]
819+ where
820+ strings = map show (toList m)
821+ widest = maximum $ map length strings
781822 fill str = replicate (widest - length str) ' ' ++ str
782− blank = fill ""
823+ blank = fill ""
824+ safeGet i j m
825+ | i > rows m || j > columns m || i < 1 || j < 1 = Nothing
826+ | otherwise = Just $ unsafeGet i j m (toList m)
827+ unsafeGet i j m l = l !! encode (columns m) (i,j)
828+ encode m (i,j) = (i-1)*m + j - 1
829+ getElem i j m =
830+ fromMaybe
831+ (error $
832+ "getElem: Trying to get the "
833+ ++ show (i, j)
834+ ++ " element from a "
835+ ++ show (rows m) ++ "x" ++ show (columns m)
836+ ++ " matrix."
837+ )
838+ (safeGet i j m)
783839
784840-- | Matrix pretty printer
785−prettyPrint :: (KnownNat (Count cols), Show e) => Matrix e cols rows -> IO ()
841+prettyPrint :: (CountableDims cols rows, Show e) => Matrix e cols rows -> IO ()
786842prettyPrint = putStrLn . pretty
787843
844+-- | Zip two matrices with a given binary function
845+zipWithM :: (e -> f -> g) -> Matrix e cols rows -> Matrix f cols rows -> Matrix g cols rows
846+zipWithM f (One a) (One b) = One (f a b)
847+zipWithM f (Join a b) (Join c d) = Join (zipWithM f a c) (zipWithM f b d)
848+zipWithM f (Fork a b) (Fork c d) = Fork (zipWithM f a c) (zipWithM f b d)
849+zipWithM f x@(Fork _ _) y@(Join _ _) = zipWithM f x (abideJF y)
850+zipWithM f x@(Join _ _) y@(Fork _ _) = zipWithM f (abideJF x) y
851+
788852-- Relational operators functions
789853
854+type Boolean = Natural 0 1
855+type Relation a b = Matrix Boolean a b
856+
790857-- | Helper conversion function
791858toBool :: (Num e, Eq e) => e -> Bool
792859toBool n
@@ -799,143 +866,109 @@ fromBool True = nat 1
799866fromBool False = nat 0
800867
801868-- | Relational negation
802−negateM :: Matrix (Natural 0 1) cols rows -> Matrix (Natural 0 1) cols rows
803−negateM Empty = Empty
804−negateM (One (Nat 0)) = One (Nat 1)
805−negateM (One (Nat 1)) = One (Nat 0)
806−negateM (Junc a b) = Junc (negateM a) (negateM b)
807−negateM (Split a b) = Split (negateM a) (negateM b)
869+negateM :: Relation cols rows -> Relation cols rows
870+negateM (One (Nat p)) = One (Nat (negate p))
871+negateM (Join a b) = Join (negateM a) (negateM b)
872+negateM (Fork a b) = Fork (negateM a) (negateM b)
808873
809874-- | Relational addition
810−orM :: Matrix (Natural 0 1) cols rows -> Matrix (Natural 0 1) cols rows -> Matrix (Natural 0 1) cols rows
811−orM Empty Empty = Empty
812−orM (One a) (One b) = One (fromBool (toBool a || toBool b))
813−orM (Junc a b) (Junc c d) = Junc (orM a c) (orM b d)
814−orM (Split a b) (Split c d) = Split (orM a c) (orM b d)
815−orM x@(Split _ _) y@(Junc _ _) = orM x (abideJS y)
816−orM x@(Junc _ _) y@(Split _ _) = orM (abideJS x) y
875+orM :: Relation cols rows -> Relation cols rows -> Relation cols rows
876+orM (One a) (One b) = One (fromBool (toBool a || toBool b))
877+orM (Join a b) (Join c d) = Join (orM a c) (orM b d)
878+orM (Fork a b) (Fork c d) = Fork (orM a c) (orM b d)
879+orM x@(Fork _ _) y@(Join _ _) = orM x (abideJF y)
880+orM x@(Join _ _) y@(Fork _ _) = orM (abideJF x) y
817881
818882-- | Relational multiplication
819−andM :: Matrix (Natural 0 1) cols rows -> Matrix (Natural 0 1) cols rows -> Matrix (Natural 0 1) cols rows
820−andM Empty Empty = Empty
821−andM (One a) (One b) = One (fromBool (toBool a && toBool b))
822−andM (Junc a b) (Junc c d) = Junc (andM a c) (andM b d)
823−andM (Split a b) (Split c d) = Split (andM a c) (andM b d)
824−andM x@(Split _ _) y@(Junc _ _) = andM x (abideJS y)
825−andM x@(Junc _ _) y@(Split _ _) = andM (abideJS x) y
883+andM :: Relation cols rows -> Relation cols rows -> Relation cols rows
884+andM (One a) (One b) = One (fromBool (toBool a && toBool b))
885+andM (Join a b) (Join c d) = Join (andM a c) (andM b d)
886+andM (Fork a b) (Fork c d) = Fork (andM a c) (andM b d)
887+andM x@(Fork _ _) y@(Join _ _) = andM x (abideJF y)
888+andM x@(Join _ _) y@(Fork _ _) = andM (abideJF x) y
826889
827890-- | Relational subtraction
828−subM :: Matrix (Natural 0 1) cols rows -> Matrix (Natural 0 1) cols rows -> Matrix (Natural 0 1) cols rows
829−subM Empty Empty = Empty
830−subM (One a) (One b) = if a - b < nat 0 then One (nat 0) else One (a - b)
831−subM (Junc a b) (Junc c d) = Junc (subM a c) (subM b d)
832−subM (Split a b) (Split c d) = Split (subM a c) (subM b d)
833−subM x@(Split _ _) y@(Junc _ _) = subM x (abideJS y)
834−subM x@(Junc _ _) y@(Split _ _) = subM (abideJS x) y
891+subM :: Relation cols rows -> Relation cols rows -> Relation cols rows
892+subM (One a) (One b) = if a - b < nat 0 then One (nat 0) else One (a - b)
893+subM (Join a b) (Join c d) = Join (subM a c) (subM b d)
894+subM (Fork a b) (Fork c d) = Fork (subM a c) (subM b d)
895+subM x@(Fork _ _) y@(Join _ _) = subM x (abideJF y)
896+subM x@(Join _ _) y@(Fork _ _) = subM (abideJF x) y
835897
836898-- | Matrix relational composition.
837−compRel :: Matrix (Natural 0 1) cr rows -> Matrix (Natural 0 1) cols cr -> Matrix (Natural 0 1) cols rows
838−compRel Empty Empty = Empty
839−compRel (One a) (One b) = One (fromBool (toBool a && toBool b))
840−compRel (Junc a b) (Split c d) = orM (compRel a c) (compRel b d) -- Divide-and-conquer law
841−compRel (Split a b) c = Split (compRel a c) (compRel b c) -- Split fusion law
842−compRel c (Junc a b) = Junc (compRel c a) (compRel c b) -- Junc fusion law
899+compRel :: Relation cr rows -> Relation cols cr -> Relation cols rows
900+compRel (One a) (One b) = One (fromBool (toBool a && toBool b))
901+compRel (Join a b) (Fork c d) = orM (compRel a c) (compRel b d) -- Divide-and-conquer law
902+compRel (Fork a b) c = Fork (compRel a c) (compRel b c) -- Fork fusion law
903+compRel c (Join a b) = Join (compRel c a) (compRel c b) -- Join fusion law
904+
905+-- | Matrix relational right division
906+divR :: Relation b c -> Relation b a -> Relation a c
907+divR (One a) (One b) = One (fromBool (not (toBool b) || toBool a)) -- b implies a
908+divR (Join a b) (Join c d) = andM (divR a c) (divR b d)
909+divR (Fork a b) c = Fork (divR a c) (divR b c)
910+divR c (Fork a b) = Join (divR c a) (divR c b)
911+
912+-- | Matrix relational left division
913+divL :: Relation c b -> Relation a b -> Relation a c
914+divL x y = tr (divR (tr y) (tr x))
915+
916+-- | Matrix relational symmetric division
917+divS :: Relation c a -> Relation b a -> Relation c b
918+divS s r = divL r s `intersection` divR (tr r) (tr s)
919+ where
920+ intersection = andM
843921
844922-- | Lifts functions to relations with arbitrary dimensions.
845923--
846924-- NOTE: Be careful to not ask for a relation bigger than the cardinality of
847925-- types @a@ or @b@ allows.
848−fromFRel ::
926+fromFRel' ::
849927 forall a b cols rows.
850− ( Bounded a,
851− Bounded b,
852− Enum a,
853− Enum b,
854− Eq b,
855− KnownNat (Count cols),
856− KnownNat (Count rows),
857− FromLists (Natural 0 1) rows cols
928+ ( Liftable Boolean a b,
929+ CountableDims cols rows,
930+ FL rows cols
858931 ) =>
859932 (a -> b) ->
860− Matrix (Natural 0 1) cols rows
861−fromFRel f =
862− let minA = minBound @a
863− maxA = maxBound @a
864− minB = minBound @b
865− maxB = maxBound @b
866− ccols = fromInteger $ natVal (Proxy :: Proxy (Count cols))
867− rrows = fromInteger $ natVal (Proxy :: Proxy (Count rows))
868− elementsA = take ccols [minA .. maxA]
869− elementsB = take rrows [minB .. maxB]
870− combinations = (,) <$> elementsA <*> elementsB
871− combAp = map snd . sort . map (\(a, b) -> if f a == b
872− then ((fromEnum a, fromEnum b), nat 1)
873− else ((fromEnum a, fromEnum b), nat 0)) $ combinations
874− mList = buildList combAp rrows
875− in tr $ fromLists mList
876− where
877− buildList [] _ = []
878− buildList l r = take r l : buildList (drop r l) r
933+ Relation cols rows
934+fromFRel' = fromF'
879935
880936-- | Lifts functions to relations with dimensions matching @a@ and @b@
881937-- cardinality's.
882−fromFRel' ::
938+fromFRel ::
883939 forall a b.
884− ( Bounded a,
885− Bounded b,
886− Enum a,
887− Enum b,
888− Eq b,
889− KnownNat (Count (Normalize a)),
890− KnownNat (Count (Normalize b)),
891− FromLists (Natural 0 1) (Normalize b) (Normalize a)
940+ ( Liftable Boolean a b,
941+ CountableDimsN a b,
942+ FLN b a
892943 ) =>
893944 (a -> b) ->
894− Matrix (Natural 0 1) (Normalize a) (Normalize b)
895−fromFRel' f =
896− let minA = minBound @a
897− maxA = maxBound @a
898− minB = minBound @b
899− maxB = maxBound @b
900− ccols = fromInteger $ natVal (Proxy :: Proxy (Count (Normalize a)))
901− rrows = fromInteger $ natVal (Proxy :: Proxy (Count (Normalize b)))
902− elementsA = take ccols [minA .. maxA]
903− elementsB = take rrows [minB .. maxB]
904− combinations = (,) <$> elementsA <*> elementsB
905− combAp = map snd . sort . map (\(a, b) -> if f a == b
906− then ((fromEnum a, fromEnum b), nat 1)
907− else ((fromEnum a, fromEnum b), nat 0)) $ combinations
908− mList = buildList combAp rrows
909− in tr $ fromLists mList
910− where
911− buildList [] _ = []
912− buildList l r = take r l : buildList (drop r l) r
945+ Relation (Normalize a) (Normalize b)
946+fromFRel = fromFRel'
913947
914948-- | Lifts a relation function to a Boolean Matrix
915−toRel ::
949+toRel ::
916950 forall a b.
917951 ( Bounded a,
918952 Bounded b,
919953 Enum a,
920954 Enum b,
921955 Eq b,
922− KnownNat (Count (Normalize a)),
923− KnownNat (Count (Normalize b)),
924− FromLists (Natural 0 1) (Normalize b) (Normalize a)
925− )
926− => (a -> b -> Bool) -> Matrix (Natural 0 1) (Normalize a) (Normalize b)
956+ CountableDims a b,
957+ FLN b a
958+ )
959+ => (a -> b -> Bool) -> Relation (Normalize a) (Normalize b)
927960toRel f =
928961 let minA = minBound @a
929962 maxA = maxBound @a
930963 minB = minBound @b
931964 maxB = maxBound @b
932− ccols = fromInteger $ natVal (Proxy :: Proxy (Count (Normalize a)))
933− rrows = fromInteger $ natVal (Proxy :: Proxy (Count (Normalize b)))
965+ ccols = fromInteger $ natVal (Proxy :: Proxy (Count a))
966+ rrows = fromInteger $ natVal (Proxy :: Proxy (Count b))
934967 elementsA = take ccols [minA .. maxA]
935968 elementsB = take rrows [minB .. maxB]
936969 combinations = (,) <$> elementsA <*> elementsB
937− combAp = map snd . sort . map (\(a, b) -> if uncurry f (a, b)
938− then ((fromEnum a, fromEnum b), nat 1)
970+ combAp = map snd . sort . map (\(a, b) -> if uncurry f (a, b)
971+ then ((fromEnum a, fromEnum b), nat 1)
939972 else ((fromEnum a, fromEnum b), nat 0)) $ combinations
940973 mList = buildList combAp rrows
941974 in tr $ fromLists mList