on master help sign in
34 files changed+4723−2444
since splitsnapshots
unifiedsplit
.github/workflows/ci.yml+43 .gitignore+54−2 .travis.yml+47 CHANGELOG.md+17 ChangeLog.md−3 LICENSE+17−26 README.md+167−81 Setup.hs−2 app/Main.hs−88 appveyor.yml+34 benchmark/Main.hs+175 laop.cabal+89 package.yaml−48 src/Dist/Internal.hs−99 src/Dist.hs → src/LAoP/Dist.hs+28−3 src/LAoP/Dist/Internal.hs+224 src/LAoP/Matrix/Internal.hs+977 src/LAoP/Matrix/Nat.hs+490 src/LAoP/Matrix/Type.hs+707 src/LAoP/Relation.hs+165 src/LAoP/Relation/Internal.hs+1008 src/Utils.hs → src/LAoP/Utils.hs+10−3 src/LAoP/Utils/Internal.hs+196 src/Matrix/Internal.hs−781 src/Matrix/Nat.hs−488 src/Matrix/Type.hs−591 src/Utils/Internal.hs−158 stack-8.8.3.yaml+1 stack.yaml+1−66 stack.yaml.lock+4−4 test/Examples/Quantum.hs+31 test/Examples/Readme.hs+184 test/Examples/Spreadsheets.hs+47 test/Spec.hs+7−1
.github/workflows/ci.ymlnew file+43
@@ -0,0 +1,43 @@
1+name: CI
2+
3+# Trigger the workflow on push or pull request, but only for the master branch
4+on:
5+ pull_request:
6+ push:
7+ branches: [master]
8+
9+jobs:
10+ build:
11+ name: ghc ${{ matrix.ghc }}
12+ runs-on: ubuntu-16.04
13+ strategy:
14+ matrix:
15+ cabal: ["3.0"]
16+ ghc:
17+ - "8.6.5"
18+ - "8.8.3"
19+
20+ steps:
21+ - uses: actions/checkout@v2
22+ if: github.event.action == 'opened' || github.event.action == 'synchronize' || github.event.ref == 'refs/heads/master'
23+
24+ - uses: actions/setup-haskell@v1
25+ name: Setup Haskell
26+ with:
27+ ghc-version: ${{ matrix.ghc }}
28+ cabal-version: ${{ matrix.cabal }}
29+
30+ - uses: actions/cache@v1
31+ name: Cache ~/.cabal/store
32+ with:
33+ path: ~/.cabal/store
34+ key: ${{ runner.os }}-${{ matrix.ghc }}-cabal
35+
36+ - name: Build
37+ run: |
38+ cabal v2-update
39+ cabal v2-build --enable-tests --enable-benchmarks
40+
41+ - name: Test
42+ run: |
43+ cabal v2-test --enable-tests
.gitignore+54−2
@@ -1,3 +1,55 @@
1+### Haskell
2+dist
3+dist-*
4+cabal-dev
5+*.o
6+*.hi
7+*.chi
8+*.chs.h
9+*.dyn_o
10+*.dyn_hi
11+*.prof
12+*.aux
13+*.hp
14+*.eventlog
15+.virtualenv
16+.hsenv
17+.hpc
18+.cabal-sandbox/
19+cabal.sandbox.config
20+cabal.config
21+cabal.project.local
22+.ghc.environment.*
23+.HTF/
24+# Stack
125.stack-work/
2−laop.cabal
3−*~
26+stack.yaml.lock
27+
28+### IDE/support
29+# Vim
30+[._]*.s[a-v][a-z]
31+[._]*.sw[a-p]
32+[._]s[a-v][a-z]
33+[._]sw[a-p]
34+*~
35+tags
36+
37+# IntellijIDEA
38+.idea/
39+.ideaHaskellLib/
40+*.iml
41+
42+# Atom
43+.haskell-ghc-mod.json
44+
45+# VS
46+.vscode/
47+
48+# Emacs
49+*#
50+.dir-locals.el
51+TAGS
52+
53+# other
54+.DS_Store
55+hackage.sh
.travis.ymlnew file+47
@@ -0,0 +1,47 @@
1+sudo: true
2+language: haskell
3+
4+git:
5+ depth: 5
6+
7+cabal: "3.0"
8+
9+cache:
10+ directories:
11+ - "$HOME/.cabal/store"
12+ - "$HOME/.stack"
13+ - "$TRAVIS_BUILD_DIR/.stack-work"
14+
15+matrix:
16+ include:
17+ - ghc: 8.6.5
18+ - ghc: 8.8.3
19+
20+ - ghc: 8.8.3
21+ env: STACK_YAML="$TRAVIS_BUILD_DIR/stack-8.8.3.yaml"
22+
23+ - ghc: 8.6.5
24+ env: STACK_YAML="$TRAVIS_BUILD_DIR/stack.yaml"
25+
26+
27+install:
28+ - |
29+ if [ -z "$STACK_YAML" ]; then
30+ cabal v2-update
31+ cabal v2-build --enable-tests --enable-benchmarks
32+ else
33+ curl -sSL https://get.haskellstack.org/ | sh
34+ stack --version
35+ stack build --system-ghc --test --bench --no-run-tests --no-run-benchmarks
36+ fi
37+
38+script:
39+ - |
40+ if [ -z "$STACK_YAML" ]; then
41+ cabal v2-test --enable-tests
42+ else
43+ stack test --system-ghc
44+ fi
45+
46+notifications:
47+ email: false
CHANGELOG.mdnew file+17
@@ -0,0 +1,17 @@
1+# Changelog
2+
3+`laop` uses [PVP Versioning][1].
4+The changelog is available [on GitHub][2].
5+
6+## 0.1.1.1
7+
8+* Bump base version to work with cabal
9+
10+## 0.1.1.0
11+
12+* Package is more organized and now has tests and benchmarks separated
13+* Repository is more organized and clean
14+* Added CI
15+
16+[1]: https://pvp.haskell.org
17+[2]: https://github.com/bolt12/laop2/releases
ChangeLog.mddeleted−3
@@ -1,3 +0,0 @@
1−# Changelog for laop
2−
3−## Unreleased changes
LICENSE+17−26
@@ -1,30 +1,21 @@
1−Copyright Armando Santos (c) 2019
1+MIT License
22
3−All rights reserved.
3+Copyright (c) 2020 Armando Santos
44
5−Redistribution and use in source and binary forms, with or without
6−modification, are permitted provided that the following conditions are met:
5+Permission is hereby granted, free of charge, to any person obtaining a copy
6+of this software and associated documentation files (the "Software"), to deal
7+in the Software without restriction, including without limitation the rights
8+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+copies of the Software, and to permit persons to whom the Software is
10+furnished to do so, subject to the following conditions:
711
8− * Redistributions of source code must retain the above copyright
9− notice, this list of conditions and the following disclaimer.
12+The above copyright notice and this permission notice shall be included in all
13+copies or substantial portions of the Software.
1014
11− * Redistributions in binary form must reproduce the above
12− copyright notice, this list of conditions and the following
13− disclaimer in the documentation and/or other materials provided
14− with the distribution.
15−
16− * Neither the name of Armando Santos nor the names of other
17− contributors may be used to endorse or promote products derived
18− from this software without specific prior written permission.
19−
20−THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21−"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22−LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
23−A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
24−OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
25−SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
26−LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
27−DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
28−THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
29−(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
30−OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
15+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+SOFTWARE.
README.md+167−81
@@ -1,42 +1,62 @@
11# laop - Linear Algebra of Programming library
22
3+[![GitHub CI](https://github.com/bolt12/laop/workflows/CI/badge.svg)](https://github.com/bolt12/laop/actions)
4+[![Build status](https://img.shields.io/travis/bolt12/laop.svg?logo=travis)](https://travis-ci.org/bolt12/laop)
5+[![Hackage](https://img.shields.io/hackage/v/laop.svg?logo=haskell)](https://hackage.haskell.org/package/laop)
6+[![Stackage Lts](http://stackage.org/package/laop/badge/lts)](http://stackage.org/lts/package/laop)
7+[![Stackage Nightly](http://stackage.org/package/laop/badge/nightly)](http://stackage.org/nightly/package/laop)
8+
39The LAoP discipline generalises relations and functions treating them as
410Boolean matrices and in turn consider these as arrows.
511
612__LAoP__ is a library for algebraic (inductive) construction and manipulation of matrices
7−in Haskell. See <https://github.com/bolt12/master-thesis my Msc Thesis> for the
13+in Haskell. See [my Msc Thesis](https://github.com/bolt12/master-thesis) for the
814motivation behind the library, the underlying theory, and implementation details.
915
1016This module offers many of the combinators mentioned in the work of
11−Macedo (2012) and Oliveira (2012).
17+[Macedo (2012)](https://repositorium.sdum.uminho.pt/handle/1822/22894) and [Oliveira (2012)](https://pdfs.semanticscholar.org/ccf5/27fa9179081223bffe8067edd81948644fc0.pdf).
18+
19+See the package in hackage [here](https://hackage.haskell.org/package/laop-0.1.1.0)
20+
21+A Functional Pearl has been written and can be regarded as the [reference document](https://github.com/bolt12/tymfgg-pearl) for this library.
1222
1323## Features
1424
15−This library offers:
16−
17−- One that uses normal datatypes (`Void`, `()`, `Either`) for matrix dimensions and two
18− type families `FromNat` and `Count` to make it easier to work with these type of matrices.
19−- Other that uses type level naturals for the dimensions and is just a newtype wrapper
20− around the other matrix data type.
21−- A very simple Probabilistic Programming module and several functions and data types to
22− make it easier to deal with sample space.
23−
24−Given this, this new matrix formulation compared to other libraries one has much more advantages, such as:
25−
26−- Has an inductive definition enabling writing matrix manipulation functions in a much more elegant and calculational way;
27−- Statically typed dimensions;
28−- Polymorphic data type dimensions;
29−- Polymorphic matrix content;
30−- Awesome dimension type inference;
31−- Fast type natural conversion via `FromNat` type family;
32−- Matrix `Junc` and `Split`-ing in O(1);
33−- Matrix composition takes advantage of divide-and-conquer and fusion laws.
34−
35−Unfortunately, this approach does not solve the issue of type dimensions being in some way constrainted making it impossible to write Arrow instances, for example. Type inference isn't perfect, when it comes to infer the types of matrices which dimensions are computed using type level naturals multiplication, the compiler needs type annotations in order to succeed.
25+This library offers 3 main matrix programming modules:
26+
27+- One in which matrices are typed with type level natural numbers;
28+- One in which matrices are typed with arbitrary generic data types;
29+- One in which matrices are regarded as relations, i.e. boolean matrices;
30+
31+There's also an experimental module that uses matrices to represent probability
32+distributions.
33+
34+The most interesting feature is that matrices are represented as an inductive data type.
35+Given this formulation, matrix algorithms can be expressed in a much more elegant and
36+calculational style than the traditional vector of vectors representation. This data type
37+guarantees that a matrix will always have valid dimensions. It can also express block matrix
38+computations naturally, which leads to total, efficient and statically typed manipulation
39+and transformation functions.
40+
41+Like matrix multiplication, other common operations, such as matrix transposition, benefit from a block-oriented structure that leads to a simple and natural divide-and-conquer algorithmic solution. Performance wise, this means that without much effort we can obtain optimal cache-oblivious algorithms.
42+
43+Given this, this new matrix formulation compared to other libraries:
44+
45+- Is more compositional and polymorphic and does not have partial matrix manipulation functions (hence less chances for usage errors);
46+- Our implementation of matrices enables simple manipulation of submatrices, making it particularly suitable for formal verification and equation reasoning, using the mathematical framework defined by the linear algebra of programming. Furthermore, the data type constructors ensure that the matrices of this kind are sound, i.e. malformed matrices with incorrect dimensions of the sort, can not be constructed.
47+
48+## Known issues
49+
50+Unfortunately, due to the use of type-level programming features, this approach sometimes requires type dimensions to be constrainted, in some way, impossible to write idiomatic Arrow instances, for example. Type inference isn't perfect, when it comes to infer the types of matrices which dimensions are computed using type level naturals multiplication, the compiler needs type annotations in order to succeed. And not all kinds of programs can be modeled using matrices, namely programs that deal with arbitrary infinite data types such as lists or integers (although there are some workarounds).
51+
52+## Notes
53+
54+This is still a work in progress, any feedback is welcome!
3655
3756## Example
3857
3958```Haskell
59+{-# LANGUAGE DeriveGeneric #-}
4060{-# LANGUAGE FlexibleContexts #-}
4161{-# LANGUAGE TypeOperators #-}
4262{-# LANGUAGE TypeApplications #-}
@@ -44,29 +64,32 @@ Unfortunately, this approach does not solve the issue of type dimensions being i
4464
4565module Main where
4666
47−import Matrix.Nat
67+import Matrix.Type
4868import Utils
4969import Dist
5070import GHC.TypeLits
5171import Data.Coerce
72+import GHC.Generics
73+import Control.Category hiding (id)
74+import Prelude hiding ((.))
5275
5376-- Monty Hall Problem
5477data Outcome = Win | Lose
55− deriving (Bounded, Enum, Eq, Show)
78+ deriving (Bounded, Enum, Eq, Show, Generic)
5679
5780switch :: Outcome -> Outcome
5881switch Win = Lose
5982switch Lose = Win
6083
61−firstChoice :: Dist Outcome m
84+firstChoice :: Matrix Double () Outcome
6285firstChoice = col [1/3, 2/3]
6386
64−secondChoice :: Matrix Double 2 2
65−secondChoice = fromF switch
87+secondChoice :: Matrix Double Outcome Outcome
88+secondChoice = fromF' switch
6689
6790-- Dice sum
6891
69−type SS = Natural 1 6
92+type SS = Natural 1 6 -- Sample Space
7093
7194sumSS :: SS -> SS -> Natural 2 12
7295sumSS = coerceNat (+)
@@ -81,49 +104,121 @@ condition (fst, snd) thrd = if fst == snd
81104conditionSS :: (SS, SS) -> SS -> Natural 3 18
82105conditionSS = coerceNat2 condition
83106
84−conditionalThrows = fromF' (uncurry conditionSS) `comp` khatri die (khatri die die)
107+conditionalThrows = fromF' (uncurry conditionSS) . khatri (khatri die die) die
85108
86−die :: Dist (Natural 1 6) 6
87−die = uniform [nat @1 @6 1 .. nat 6]
109+die :: Matrix Double () SS
110+die = col $ map (const (1/6)) [nat @1 @6 1 .. nat 6]
88111
89112-- Sprinkler
90113
91−rain :: Dist Bool 2
92−rain = choose 0.8
114+rain :: Matrix Double () Bool
115+rain = col [0.8, 0.2]
93116
94−sprinkler :: Matrix Double 2 2
117+sprinkler :: Matrix Double Bool Bool
95118sprinkler = fromLists [[0.6, 0.99], [0.4, 0.01]]
96119
97−grass :: Matrix Double 4 2
120+grass :: Matrix Double (Bool, Bool) Bool
98121grass = fromLists [[1, 0.2, 0.1, 0.01], [0, 0.8, 0.9, 0.99]]
99122
100−state = khatri grass identity `comp` khatri sprinkler identity `comp` rain
123+state :: Matrix Double () (Bool, (Bool, Bool))
124+state = khatri grass identity . khatri sprinkler identity . rain
125+
126+grass_wet :: Matrix Double (Bool, (Bool, Bool)) One
127+grass_wet = row [0,1] . kp1
128+
129+rainning :: Matrix Double (Bool, (Bool, Bool)) One
130+rainning = row [0,1] . kp2 . kp2
131+
132+-- Alcuin Puzzle
133+
134+data Being = Farmer | Fox | Goose | Beans
135+ deriving (Bounded, Enum, Eq, Show, Generic)
136+
137+data Bank = LeftB | RightB
138+ deriving (Bounded, Enum, Eq, Show, Generic)
139+
140+eats :: Being -> Being -> Bool
141+eats Fox Goose = True
142+eats Goose Beans = True
143+eats _ _ = False
144+
145+eatsR :: R.Relation Being Being
146+eatsR = R.toRel eats
147+
148+cross :: Bank -> Bank
149+cross LeftB = RightB
150+cross RightB = LeftB
151+
152+crossR :: R.Relation Bank Bank
153+crossR = R.fromF' cross
154+
155+-- | Initial state, everyone in the left bank
156+locationLeft :: Being -> Bank
157+locationLeft _ = LeftB
158+
159+locationLeftR :: R.Relation Being Bank
160+locationLeftR = R.fromF' locationLeft
101161
102−grass_wet = row [0,1] `comp` kp1 @Double @2 @4
162+-- | Initial state, everyone in the right bank
163+locationRight :: Being -> Bank
164+locationRight _ = RightB
103165
104−rainning = row [0,1] `comp` kp2 @Double @2 @2 `comp` kp2 @Double @2 @4
166+locationRightR :: R.Relation Being Bank
167+locationRightR = R.fromF' locationRight
168+
169+-- Properties
170+
171+-- Being at the same bank
172+sameBank :: R.Relation Being Bank -> R.Relation Being Being
173+sameBank = R.ker
174+
175+-- Risk of somebody eating somebody else
176+canEat :: R.Relation Being Bank -> R.Relation Being Being
177+canEat w = sameBank w `R.intersection` eatsR
178+
179+-- "Starvation" property.
180+inv :: R.Relation Being Bank -> Bool
181+inv w = (w `R.comp` canEat w) `R.sse` (w `R.comp` farmer)
182+ where
183+ farmer :: R.Relation Being Being
184+ farmer = R.fromF' (const Farmer)
185+
186+-- Arbitrary state
187+bankState :: Being -> Bank -> Bool
188+bankState Farmer LeftB = True
189+bankState Fox LeftB = True
190+bankState Goose RightB = True
191+bankState Beans RightB = True
192+bankState _ _ = False
193+
194+bankStateR :: R.Relation Being Bank
195+bankStateR = R.toRel bankState
196+
197+-- Main
105198
106199main :: IO ()
107200main = do
108201 putStrLn "Monty Hall Problem solution:"
109− prettyPrint (p1 @Double @1 `comp` secondChoice `comp` firstChoice)
202+ prettyPrint (secondChoice . firstChoice)
110203 putStrLn "\n Sum of dices probability:"
111204 prettyPrint (sumSSM `comp` khatri die die)
112− prettyPrintDist @(Natural 2 12) (sumSSM `comp` khatri die die)
113205 putStrLn "\n Conditional dice throw:"
114− prettyPrintDist @(Natural 3 18) conditionalThrows
206+ prettyPrint conditionalThrows
115207 putStrLn "\n Checking that the last result is indeed a distribution: "
116− prettyPrint (bang `comp` sumSSM `comp` khatri die die)
208+ prettyPrint (bang . sumSSM . khatri die die)
117209 putStrLn "\n Probability of grass being wet:"
118− prettyPrint (grass_wet `comp` state)
210+ prettyPrint (grass_wet . state)
119211 putStrLn "\n Probability of rain:"
120− prettyPrint (rainning `comp` state)
212+ prettyPrint (rainning . state)
213+ putStrLn "\n Is the arbitrary state a valid state? (Alcuin Puzzle)"
214+ print (inv bankStateR)
121215```
122216
123217```Shell
124218Monty Hall Problem solution:
125219┌ ┐
126220│ 0.6666666666666666 │
221+│ 0.3333333333333333 │
127222└ ┘
128223
129224 Sum of dices probability:
@@ -140,37 +235,26 @@ Monty Hall Problem solution:
140235│ 5.555555555555555e-2 │
141236│ 2.7777777777777776e-2 │
142237└ ┘
143−Nat 7 16.666666666666664%
144−Nat 6 13.88888888888889%
145−Nat 8 13.88888888888889%
146−Nat 5 11.11111111111111%
147−Nat 9 11.11111111111111%
148−Nat 4 8.333333333333332%
149−Nat 10 8.333333333333332%
150−Nat 3 5.555555555555555%
151−Nat 11 5.555555555555555%
152−Nat 2 2.7777777777777777%
153−Nat 12 2.7777777777777777%
154−
155238
156239 Conditional dice throw:
157−Nat 9 12.962962962962962%
158−Nat 12 12.962962962962962%
159−Nat 10 11.11111111111111%
160−Nat 11 11.11111111111111%
161−Nat 8 8.333333333333332%
162−Nat 13 8.333333333333332%
163−Nat 6 6.481481481481481%
164−Nat 15 6.481481481481481%
165−Nat 7 5.555555555555555%
166−Nat 14 5.555555555555555%
167−Nat 3 2.7777777777777777%
168−Nat 18 2.7777777777777777%
169−Nat 5 1.8518518518518516%
170−Nat 16 1.8518518518518516%
171−Nat 4 0.9259259259259258%
172−Nat 17 0.9259259259259258%
173−
240+┌ ┐
241+│ 2.7777777777777776e-2 │
242+│ 9.259259259259259e-3 │
243+│ 1.8518518518518517e-2 │
244+│ 6.481481481481481e-2 │
245+│ 5.555555555555555e-2 │
246+│ 8.333333333333333e-2 │
247+│ 0.12962962962962962 │
248+│ 0.1111111111111111 │
249+│ 0.1111111111111111 │
250+│ 0.12962962962962962 │
251+│ 8.333333333333333e-2 │
252+│ 5.555555555555555e-2 │
253+│ 6.481481481481481e-2 │
254+│ 1.8518518518518517e-2 │
255+│ 9.259259259259259e-3 │
256+│ 2.7777777777777776e-2 │
257+└ ┘
174258
175259 Checking that the last result is indeed a distribution:
176260┌ ┐
@@ -178,13 +262,15 @@ Nat 17 0.9259259259259258%
178262└ ┘
179263
180264 Probability of grass being wet:
181−┌ ┐
182−│ 0.44838 │
183−└ ┘
265+┌ ┐
266+│ 0.4483800000000001 │
267+└ ┘
184268
185269 Probability of rain:
186−┌ ┐
187−│ 0.19999999999999998 │
188−└ ┘
189−λ>
270+┌ ┐
271+│ 0.2 │
272+└ ┘
273+
274+Is the arbitrary state a valid state? (Alcuin Puzzle)
275+False
190276```
Setup.hsdeleted−2
@@ -1,2 +0,0 @@
1−import Distribution.Simple
2−main = defaultMain
app/Main.hsdeleted−88
@@ -1,88 +0,0 @@
1−{-# LANGUAGE DeriveGeneric #-}
2−{-# LANGUAGE FlexibleContexts #-}
3−{-# LANGUAGE TypeOperators #-}
4−{-# LANGUAGE TypeApplications #-}
5−{-# LANGUAGE DataKinds #-}
6−
7−module Main where
8−
9−import Matrix.Type
10−import Utils
11−import Dist
12−import GHC.TypeLits
13−import Data.Coerce
14−import GHC.Generics
15−import Control.Category hiding (id)
16−import Prelude hiding ((.))
17−
18−-- Monty Hall Problem
19−data Outcome = Win | Lose
20− deriving (Bounded, Enum, Eq, Show, Generic)
21−
22−switch :: Outcome -> Outcome
23−switch Win = Lose
24−switch Lose = Win
25−
26−firstChoice :: Dist Outcome
27−firstChoice = col [1/3, 2/3]
28−
29−secondChoice :: Matrix Double Outcome Outcome
30−secondChoice = fromF' switch
31−
32−-- Dice sum
33−
34−type SS = Natural 1 6
35−
36−sumSS :: SS -> SS -> Natural 2 12
37−sumSS = coerceNat (+)
38−
39−sumSSM = fromF' (uncurry sumSS)
40−
41−condition :: (Int, Int) -> Int -> Int
42−condition (fst, snd) thrd = if fst == snd
43− then fst * 3
44− else fst + snd + thrd
45−
46−conditionSS :: (SS, SS) -> SS -> Natural 3 18
47−conditionSS = coerceNat2 condition
48−
49−conditionalThrows = fromF' (uncurry conditionSS) . khatri (khatri die die) die
50−
51−die :: Dist SS
52−die = uniform [nat @1 @6 1 .. nat 6]
53−
54−-- Sprinkler
55−
56−rain :: Dist Bool
57−rain = choose 0.8
58−
59−sprinkler :: Matrix Double Bool Bool
60−sprinkler = fromLists [[0.6, 0.99], [0.4, 0.01]]
61−
62−grass :: Matrix Double (Bool, Bool) Bool
63−grass = fromLists [[1, 0.2, 0.1, 0.01], [0, 0.8, 0.9, 0.99]]
64−
65−state :: Dist (Bool, (Bool, Bool))
66−state = khatri grass identity . khatri sprinkler identity . rain
67−
68−grass_wet :: Matrix Double (Bool, (Bool, Bool)) One
69−grass_wet = row [0,1] . kp1
70−
71−rainning :: Matrix Double (Bool, (Bool, Bool)) One
72−rainning = row [0,1] . kp2 . kp2
73−
74−main :: IO ()
75−main = do
76− -- putStrLn "Monty Hall Problem solution:"
77− -- prettyPrint (secondChoice . firstChoice)
78− -- putStrLn "\n Sum of dices probability:"
79− -- prettyPrint (sumSSM `comp` khatri die die)
80− -- prettyPrintDist @(Natural 2 12) (sumSSM . khatri die die)
81− -- putStrLn "\n Conditional dice throw:"
82− -- prettyPrintDist @(Natural 3 18) conditionalThrows
83− -- putStrLn "\n Checking that the last result is indeed a distribution: "
84− -- prettyPrint (bang . sumSSM . khatri die die)
85− putStrLn "\n Probability of grass being wet:"
86− prettyPrint (grass_wet . state)
87− -- putStrLn "\n Probability of rain:"
88− -- prettyPrint (rainning . state)
appveyor.ymlnew file+34
@@ -0,0 +1,34 @@
1+clone_folder: "c:\\WORK"
2+clone_depth: 5
3+
4+# Do not build feature branch with open Pull Requests
5+skip_branch_with_pr: true
6+
7+platform:
8+ - x86_64
9+
10+cache:
11+ - "C:\\SR"
12+ - dist-newstyle
13+
14+environment:
15+ global:
16+ CABOPTS: --store-dir=C:\\SR
17+
18+ matrix:
19+ - GHCVER: 8.6.5
20+
21+install:
22+ - choco source add -n mistuke -s https://www.myget.org/F/mistuke/api/v2
23+ - choco install -y cabal --version 2.4.1.0
24+ - choco install -y ghc --version 8.6.3
25+ - refreshenv
26+
27+before_build:
28+ - cabal --version
29+ - ghc --version
30+ - cabal %CABOPTS% v2-update
31+
32+build_script:
33+ - cabal %CABOPTS% v2-build --enable-tests
34+ - cabal %CABOPTS% v2-test --enable-tests
benchmark/Main.hsnew file+175
@@ -0,0 +1,175 @@
1+{-# LANGUAGE KindSignatures #-}
2+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
3+{-# LANGUAGE DerivingVia #-}
4+{-# LANGUAGE DataKinds #-}
5+{-# LANGUAGE BangPatterns #-}
6+{-# LANGUAGE TypeApplications #-}
7+{-# LANGUAGE FlexibleContexts #-}
8+{-# LANGUAGE AllowAmbiguousTypes #-}
9+{-# LANGUAGE ScopedTypeVariables #-}
10+
11+module Main (main) where
12+
13+import LAoP.Dist.Internal
14+import LAoP.Utils
15+import LAoP.Matrix.Type hiding (CountableN, Countable, FLN)
16+import qualified LAoP.Matrix.Type as T (FLN)
17+import Criterion.Main
18+import Control.DeepSeq
19+import Test.QuickCheck
20+import GHC.TypeLits
21+import Data.Proxy
22+import Prelude hiding (id, (.))
23+
24+selectM2 ::
25+ ( Num e,
26+ T.FLN b b,
27+ CountableN b
28+ ) => Matrix e cols (Either a b) -> Matrix e a b -> Matrix e cols b
29+selectM2 m y = join y iden `comp` m
30+
31+selectD2 ::
32+ ( FLN b b,
33+ CountableN b
34+ ) => Dist (Either a b) -> Matrix Prob a b -> Dist b
35+selectD2 (D d) m = D (join m iden `comp` d)
36+
37+-- Composition with iden
38+compId m = comp iden m
39+
40+randomDist :: forall a . (Countable a, FLN () a) => Gen (Dist a)
41+randomDist = do
42+ let size = fromInteger (natVal (Proxy :: Proxy (Count a)))
43+ l <- vectorOf size (arbitrary :: Gen Prob)
44+ let ln = normalize l
45+ lr = map (:[]) ln
46+ m = fromLists lr
47+ return (D m)
48+
49+randomMatrix :: forall a b . (CountableDims a b, FLN a b) => Gen (Matrix Prob a b)
50+randomMatrix = do
51+ let cols = fromInteger (natVal (Proxy :: Proxy (Count a)))
52+ rows = fromInteger (natVal (Proxy :: Proxy (Count b)))
53+ l <- vectorOf (cols * rows) arbitrary
54+ let lr = buildList l cols
55+ m = fromLists lr
56+ return m
57+
58+buildList [] _ = []
59+buildList l r = take r l : buildList (drop r l) r
60+
61+normalize :: [Prob] -> [Prob]
62+normalize l = let l' = map abs l
63+ s = sum l'
64+ in map (/ s) l'
65+
66+-- Probability
67+newtype Probability = P Double
68+ deriving (Num, Show, Fractional, NFData) via Double
69+newtype Dist' a = D' { unD :: [(a,Probability)] }
70+ deriving (Show, NFData)
71+
72+instance Functor Dist' where
73+ fmap f (D' d) = D' [(f x,p) | (x,p) <- d]
74+
75+instance Applicative Dist' where
76+ pure x = D' [(x, 1)]
77+ fm <*> m = D' [(f x,q*p) | (f,p) <- unD fm, (x,q) <- unD m]
78+
79+class Applicative f => Selective f where
80+ select :: f (Either a b) -> f (a -> b) -> f b
81+
82+instance Selective Dist' where
83+ select x y = (\e f -> either f id e) <$> x <*> y -- selectA
84+
85+instance Monad Dist' where
86+ return = pure
87+ (D' d) >>= f = D' [(y,q*p) | (x,p) <- d, (y,q) <- unD (f x)]
88+
89+normalize2 :: forall a . (Enum a, Bounded a) => [Probability] -> [(a, Probability)]
90+normalize2 l = let l' = map abs l
91+ as = [minBound .. maxBound]
92+ s = sum l'
93+ probs = map (/ s) l'
94+ in zip as probs
95+
96+randomDist2 :: forall a . (Countable a, Enum a, Bounded a) => Gen (Dist' a)
97+randomDist2 = do
98+ let size = fromInteger (natVal (Proxy :: Proxy (Count a)))
99+ l <- vectorOf size (arbitrary :: Gen Prob)
100+ let ln = normalize2 @a (map P l)
101+ return (D' ln)
102+
103+normalize3 :: forall a . [a] -> [Probability] -> [(a, Probability)]
104+normalize3 as l = let s = sum l
105+ probs = map (/ s) l
106+ in zip as probs
107+
108+randomDistF :: forall a b . (CountableDims a b, CoArbitrary a, Arbitrary b) => Gen (Dist' (a -> b))
109+randomDistF = do
110+ let a = fromInteger (natVal (Proxy :: Proxy (Count a)))
111+ b = fromInteger (natVal (Proxy :: Proxy (Count b)))
112+ size = a * b
113+ l <- vectorOf size (arbitrary :: Gen Prob)
114+ l2 <- vectorOf size (arbitrary :: Gen (a -> b))
115+ let !ln = normalize3 l2 (map P l)
116+ return (D' ln)
117+
118+instance CoArbitrary (Natural a b)
119+
120+instance forall (a :: Nat) (b :: Nat). (KnownNat a, KnownNat b) => Arbitrary (Natural a b)
121+ where
122+ arbitrary =
123+ let bottom = fromInteger (natVal (Proxy :: Proxy a))
124+ top = fromInteger (natVal (Proxy :: Proxy b))
125+ in do
126+ x <- arbitrary `suchThat` (\n -> n >= bottom && n <= top)
127+ return (nat x)
128+
129+setupEnv = do
130+ m11 <- generate (resize 1 (randomMatrix @(Natural 0 10) @(Natural 0 10) ))
131+ m12 <- generate (resize 1 (randomMatrix @(Natural 0 10) @(Natural 0 10) ))
132+ m21 <- generate (resize 1 (randomMatrix @(Natural 0 100) @(Natural 0 100) ))
133+ m22 <- generate (resize 1 (randomMatrix @(Natural 0 100) @(Natural 0 100) ))
134+ m31 <- generate (resize 1 (randomMatrix @(Natural 0 200) @(Natural 0 200) ))
135+ m32 <- generate (resize 1 (randomMatrix @(Natural 0 200) @(Natural 0 200) ))
136+ return (m11, m12, m21, m22, m31, m32)
137+
138+setupEnv2 = do
139+ m21 <- generate (resize 1 (randomMatrix @(Natural 0 100) @(Natural 0 100) ))
140+ m40 <- generate (resize 1 (randomMatrix @(Natural 0 100) @(Either (Natural 0 100) (Natural 0 100) )))
141+ dist <- generate (resize 1 (randomDist @(Either (Natural 0 100) (Natural 0 100)) ))
142+ dist2 <- generate (resize 1 (randomMatrix @(Natural 0 100) @(Natural 0 100) ))
143+ distList1 <- generate (resize 1 (randomDist2 @(Either (Natural 0 100) (Natural 0 100))))
144+ distList2 <- generate (resize 1 (randomDistF @(Natural 0 100) @(Natural 0 100)))
145+ return (m21, m40, dist, dist2, distList1, distList2)
146+
147+main :: IO ()
148+main = defaultMain [
149+ env setupEnv $ \ ~(m11, m12, m21, m22, m31, m32) -> bgroup "Matrix Composition" [
150+ bgroup "10x10" [
151+ bench "WHNF - 10x10" $ whnf (comp m11) m12
152+ , bench "NF - 10x10" $ nf (comp m11) m12
153+ ],
154+ bgroup "100x100" [
155+ bench "WHNF - 100x100" $ whnf (comp m21) m22
156+ , bench "NF - 100x100" $ nf (comp m21) m22
157+ ],
158+ bgroup "200x200" [
159+ bench "WHNF - 200x200" $ whnf (comp m31) m32
160+ , bench "NF - 200x200" $ nf (comp m31) m32
161+ ],
162+ bgroup "200x200 - RULES" [
163+ bench "No rules - 200x200" $ nf (comp m21) iden
164+ , bench "Rules - 200x200" $ nf compId m21
165+ ] ],
166+ env setupEnv2 $ \ ~(m21, m40, dist, dist2, dl1, dl2) -> bgroup "Matrix vs List - `select`" [
167+ bgroup "Distribution `select` - 100+100 / 100x100" [
168+ bench "List Distribution - Applicative version" $ nf (select dl1) dl2
169+ , bench "Matrix Distribution - Applicative version" $ nf (selectD2 dist) dist2
170+ , bench "Matrix Distribution - Selective version" $ nf (selectD dist) dist2
171+ ],
172+ bgroup "Matrix `select` - 100x(100+100) / 100x100" [
173+ bench "Applicative version" $ nf (selectM2 m40) m21
174+ , bench "Selective version" $ nf (selectM m40) m21
175+ ] ] ]
laop.cabalnew file+89
@@ -0,0 +1,89 @@
1+cabal-version: 2.4
2+name: laop
3+version: 0.1.1.1
4+synopsis: Matrix programming library
5+description: Matrix programming library that uses a type-safe inductive definition
6+ inspired by the Linear Algebra of Programming
7+homepage: https://github.com/bolt12/laop
8+bug-reports: https://github.com/bolt12/laop/issues
9+license: MIT
10+license-file: LICENSE
11+author: Armando Santos
12+maintainer: Armando Santos <armandoifsantos@gmail.com>
13+copyright: 2020 Armando Santos
14+category: Data
15+build-type: Simple
16+extra-doc-files: README.md
17+ CHANGELOG.md
18+tested-with: GHC == 8.6.5
19+ GHC == 8.8.3
20+
21+source-repository head
22+ type: git
23+ location: https://github.com/bolt12/laop.git
24+
25+common common-options
26+ build-depends: base >= 4.12.0.0 && < 5,
27+ deepseq
28+
29+ ghc-options: -Wall
30+ -Wcompat
31+ -Widentities
32+ -Wincomplete-uni-patterns
33+ -Wincomplete-record-updates
34+ if impl(ghc >= 8.0)
35+ ghc-options: -Wredundant-constraints
36+ if impl(ghc >= 8.2)
37+ ghc-options: -fhide-source-paths
38+ if impl(ghc >= 8.4)
39+ ghc-options: -Wmissing-export-lists
40+ -Wpartial-fields
41+ if impl(ghc >= 8.8)
42+ ghc-options: -Wmissing-deriving-strategies
43+
44+ default-language: Haskell2010
45+
46+library
47+ import: common-options
48+ hs-source-dirs: src
49+ exposed-modules: LAoP.Dist
50+ LAoP.Dist.Internal
51+ LAoP.Matrix.Internal
52+ LAoP.Matrix.Nat
53+ LAoP.Matrix.Type
54+ LAoP.Relation
55+ LAoP.Relation.Internal
56+ LAoP.Utils
57+ LAoP.Utils.Internal
58+
59+test-suite laop-test
60+ import: common-options
61+ type: exitcode-stdio-1.0
62+ hs-source-dirs: test
63+ other-modules: Examples.Readme
64+ main-is: Spec.hs
65+ build-depends: laop
66+ ghc-options: -threaded
67+ -rtsopts
68+ -with-rtsopts=-N
69+ -funfolding-use-threshold=16
70+ -fexcess-precision
71+ -optc-O3
72+ -optc-ffast-math
73+
74+benchmark laop-benchmark
75+ import: common-options
76+ type: exitcode-stdio-1.0
77+ hs-source-dirs: benchmark
78+ main-is: Main.hs
79+ build-depends: criterion
80+ , QuickCheck
81+ , deepseq
82+ , laop
83+ ghc-options: -threaded
84+ -rtsopts
85+ -with-rtsopts=-N
86+ -funfolding-use-threshold=16
87+ -fexcess-precision
88+ -optc-O3
89+ -optc-ffast-math
package.yamldeleted−48
@@ -1,48 +0,0 @@
1−name: laop
2−version: 0.1.0.0
3−github: "bolt12/laop"
4−license: BSD3
5−author: "Armando Santos"
6−maintainer: "armandoifsantos@gmail.com"
7−copyright: "MIT"
8−
9−extra-source-files:
10−- README.md
11−- ChangeLog.md
12−
13−# Metadata used when publishing your package
14−# synopsis: Short description of your package
15−# category: Web
16−
17−# To avoid duplicated efforts in documentation and dealing with the
18−# complications of embedding Haddock markup inside cabal files, it is
19−# common to point users to the README.md file.
20−description: Please see the README on GitHub at <https://github.com/bolt12/laop#readme>
21−
22−dependencies:
23−- base >= 4.7 && < 5
24−
25−library:
26− source-dirs: src
27−
28−executables:
29− laop-exe:
30− main: Main.hs
31− source-dirs: app
32− ghc-options:
33− - -threaded
34− - -rtsopts
35− - -with-rtsopts=-N
36− dependencies:
37− - laop
38−
39−tests:
40− laop-test:
41− main: Spec.hs
42− source-dirs: test
43− ghc-options:
44− - -threaded
45− - -rtsopts
46− - -with-rtsopts=-N
47− dependencies:
48− - laop
src/Dist/Internal.hsdeleted−99
@@ -1,99 +0,0 @@
1−{-# LANGUAGE AllowAmbiguousTypes #-}
2−{-# LANGUAGE TypeApplications #-}
3−{-# LANGUAGE KindSignatures #-}
4−{-# LANGUAGE ScopedTypeVariables #-}
5−{-# LANGUAGE FlexibleContexts #-}
6−{-# LANGUAGE DataKinds #-}
7−{-# LANGUAGE RankNTypes #-}
8−
9−module Dist.Internal
10− (
11− Dist(..),
12− Prob,
13− choose,
14− shape,
15− linear,
16− uniform,
17− negExp,
18− normal,
19− toValues,
20− prettyDist,
21− prettyPrintDist
22− )
23− where
24−
25−import Matrix.Type
26−import Utils
27−import GHC.TypeLits
28−import Data.Proxy
29−import Data.List (sortBy)
30−
31−-- | Type synonym for probability value
32−type Prob = Double
33−
34−-- | Type synonym for column vector matrices. This represents a probability
35−-- distribution.
36−type Dist a = (FromLists Prob () (Normalize a)) => Matrix Prob () a
37−
38−-- | Constructs a Bernoulli distribution
39−choose :: Prob -> Dist a
40−choose prob = col [prob, 1 - prob]
41−
42−-- | Creates a distribution given a shape function
43−shape :: (Prob -> Prob) -> [a] -> Dist a
44−shape _ [] = error "Probability.shape: empty list"
45−shape f xs =
46− let incr = 1 / fromIntegral (length xs - 1)
47− ps = map f (iterate (+incr) 0)
48− in fromFreqs (zip xs ps)
49−
50−-- | Constructs a Linear distribution
51−linear :: [a] -> Dist a
52−linear = shape id
53−
54−-- | Constructs an Uniform distribution
55−uniform :: [a] -> Dist a
56−uniform = shape (const 1)
57−
58−-- | Constructs an Negative Exponential distribution
59−negExp :: [a] -> Dist a
60−negExp = shape (\x -> exp (-x))
61−
62−-- | Constructs an Normal distribution
63−normal :: [a] -> Dist a
64−normal = shape (normalCurve 0.5 0.5)
65−
66−-- | Transforms a 'Dist' into a list of pairs.
67−toValues :: forall a . (Enum a, KnownNat (Count a), FromLists Prob () (Normalize a)) => Dist a -> [(a, Prob)]
68−toValues d =
69− let rows = fromInteger (natVal (Proxy :: Proxy (Count a)))
70− probs = toList d
71− res = zip (map toEnum [0..rows]) probs
72− in res
73−
74−-- | Pretty a distribution
75−prettyDist :: forall a. (Show a, Enum a, KnownNat (Count a), FromLists Prob () (Normalize a)) => Dist a -> String
76−prettyDist d =
77− let values = sortBy (\(a, p1) (b, p2) -> compare p2 p1) (toValues @a d)
78− w = maximum (map (length . show . fst) values)
79− in concatMap
80− (\(x,p) -> showR w x ++ ' ': showProb p ++ "\n")
81− values
82− where
83− showProb p = show (p * 100) ++ "%"
84− showR n x = show x ++ " "
85−
86−-- | Pretty Print a distribution
87−prettyPrintDist :: forall a . (Show a, Enum a, KnownNat (Count a), FromLists Prob () (Normalize a)) => Dist a -> IO ()
88−prettyPrintDist = putStrLn . prettyDist @a
89−
90−-- Auxiliary functions
91−
92−fromFreqs :: [(a,Prob)] -> Dist a
93−fromFreqs xs = col (map (\(x,p) -> p/q) xs)
94− where q = sum $ map snd xs
95−
96−normalCurve :: Prob -> Prob -> Prob -> Prob
97−normalCurve mean dev x =
98− let u = (x - mean) / dev
99− in exp (-1/2 * u^(2::Int)) / sqrt (2 * pi)
src/Dist.hs → src/LAoP/Dist.hsrenamed+28−3
@@ -1,6 +1,6 @@
11-----------------------------------------------------------------------------
22-- |
3−-- Module : Dist
3+-- Module : LAoP.Dist
44-- Copyright : (c) Armando Santos 2019-2020
55-- Maintainer : armandoifsantos@gmail.com
66-- Stability : experimental
@@ -16,7 +16,7 @@
1616--
1717-----------------------------------------------------------------------------
1818
19−module Dist
19+module LAoP.Dist
2020 ( -- | If the sum of the rows of a column matrix
2121 -- is equal to 1 then this stochastic matrix
2222 -- can be seen as a probability distribution.
@@ -35,6 +35,31 @@ module Dist
3535 -- * 'Dist' and 'Prob' type synonyms
3636 Dist (..),
3737 Prob,
38+
39+ -- * Constraint type synonyms
40+ Countable,
41+ CountableN,
42+ CountableDimsN,
43+ FLN,
44+ Liftable,
45+ TrivialP,
46+
47+ -- * Functor instance equivalent functions
48+ fmapD,
49+
50+ -- * Applicative equivalent functions
51+ unitD,
52+ multD,
53+
54+ -- * Selective equivalent functions
55+ selectD,
56+ branchD,
57+ ifD,
58+
59+ -- * Monad equivalent functions
60+ returnD,
61+ bindD,
62+
3863 -- * Distribution construction functions
3964 choose,
4065 shape,
@@ -51,4 +76,4 @@ module Dist
5176 )
5277where
5378
54−import Dist.Internal
79+import LAoP.Dist.Internal
src/LAoP/Dist/Internal.hsnew file+224
@@ -0,0 +1,224 @@
1+{-# LANGUAGE DerivingVia #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE GADTs #-}
4+{-# LANGUAGE AllowAmbiguousTypes #-}
5+{-# LANGUAGE TypeApplications #-}
6+{-# LANGUAGE KindSignatures #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+{-# LANGUAGE FlexibleContexts #-}
9+{-# LANGUAGE DataKinds #-}
10+{-# LANGUAGE RankNTypes #-}
11+
12+module LAoP.Dist.Internal
13+ (
14+ Dist(..),
15+ Prob,
16+
17+ Countable,
18+ CountableN,
19+ CountableDimsN,
20+ FLN,
21+ Liftable,
22+ TrivialP,
23+
24+ fmapD,
25+ unitD,
26+ multD,
27+ selectD,
28+ branchD,
29+ ifD,
30+ returnD,
31+ bindD,
32+ (??),
33+
34+ choose,
35+ shape,
36+ linear,
37+ uniform,
38+ negExp,
39+ normal,
40+ toValues,
41+ prettyDist,
42+ prettyPrintDist
43+ )
44+ where
45+
46+import LAoP.Matrix.Type hiding (TrivialP, Countable, CountableDims, CountableN, CountableDimsN, Liftable, FLN)
47+import Prelude hiding (id, (.))
48+import qualified LAoP.Matrix.Internal as I
49+import LAoP.Utils
50+import GHC.TypeLits
51+import Data.Proxy
52+import Data.List (sortBy)
53+import Control.DeepSeq
54+import Data.Bool
55+
56+-- | Type synonym for probability value
57+type Prob = Double
58+
59+-- | Type synonym for column vector matrices. This represents a probability
60+-- distribution.
61+newtype Dist a = D (Matrix Prob () a)
62+ deriving (Show, Num, Eq, Ord, NFData) via (Matrix Prob () a)
63+
64+-- | Constraint type synonyms to keep the type signatures less convoluted
65+type Countable a = KnownNat (I.Count a)
66+type CountableN a = KnownNat (I.Count (I.Normalize a))
67+type CountableDimsN a b = (CountableN a, CountableN b)
68+type FLN a b = I.FL (I.Normalize a) (I.Normalize b)
69+type Liftable a b = (Bounded a, Bounded b, Enum a, Enum b, Eq b, Num Prob, Ord Prob)
70+type TrivialP a b = Normalize (a, b) ~ Normalize (Normalize a, Normalize b)
71+
72+-- | Functor instance
73+fmapD ::
74+ ( Liftable a b,
75+ CountableDimsN a b,
76+ FLN b a
77+ )
78+ =>
79+ (a -> b) -> Dist a -> Dist b
80+fmapD f (D m) = D (fromF' f `comp` m)
81+
82+-- | Applicative/Monoidal instance 'unit' function
83+unitD :: Dist ()
84+unitD = D (one 1)
85+
86+-- | Applicative/Monoidal instance 'mult' function
87+multD ::
88+ ( CountableDimsN a b,
89+ CountableN (a, b),
90+ FLN (a, b) a,
91+ FLN (a, b) b,
92+ TrivialP a b
93+ ) => Dist a -> Dist b -> Dist (a, b)
94+multD (D a) (D b) = D (kr a b)
95+
96+-- | Selective instance function
97+selectD ::
98+ ( FLN b b,
99+ CountableN b
100+ ) => Dist (Either a b) -> Matrix Prob a b -> Dist b
101+selectD (D d) m = D (selectM d m)
102+
103+-- | Chooses which of the two given effectful
104+-- functions to apply to a given argument;
105+branchD ::
106+ ( Num e,
107+ CountableDimsN a b,
108+ CountableDimsN c (Either b c),
109+ FLN c b,
110+ FLN a b,
111+ FLN a a,
112+ FLN b b,
113+ FLN c c,
114+ FLN b a,
115+ FLN b c,
116+ FLN (Either b c) b,
117+ FLN (Either b c) c
118+ )
119+ => Dist (Either a b) -> Matrix Prob a c -> Matrix Prob b c -> Dist c
120+branchD x l r = f x `selectD` g l `selectD` r
121+ where
122+ f (D m) = D (fork (tr i1) (i1 `comp` tr i2) `comp` m)
123+ g m = i2 `comp` m
124+
125+-- | Branch on a Boolean value, skipping unnecessary computations.
126+ifD ::
127+ ( CountableDimsN a (Either () a),
128+ FLN a a,
129+ FLN a (),
130+ FLN () a,
131+ FLN (Either () a) a
132+ )
133+ => Dist Bool -> Dist a -> Dist a -> Dist a
134+ifD x (D t) (D e) = branchD x' t e
135+ where
136+ x' = bool (Right ()) (Left ()) `fmapD` x
137+
138+-- | Monad instance 'return' function
139+returnD :: forall a . (Enum a, FLN () a, Countable a) => a -> Dist a
140+returnD a = D (col l)
141+ where
142+ i = fromInteger $ natVal (Proxy :: Proxy (Count a))
143+ x = fromEnum a
144+ l = take x [0,0..] ++ [1] ++ take (i - x - 1) [0,0..]
145+
146+-- | Monad instance '(>>=)' function
147+bindD :: Dist a -> Matrix Prob a b -> Dist b
148+bindD (D d) m = D (m `comp` d)
149+
150+-- | Extract probabilities given an Event.
151+(??) ::
152+ ( Enum a,
153+ Countable a,
154+ FLN () a
155+ ) => (a -> Bool) -> Dist a -> Prob
156+(??) p d =
157+ let l = toValues d
158+ x = filter (p . fst) l
159+ in sum . map snd $ x
160+
161+-- Distribution Construction
162+
163+-- | Constructs a Bernoulli distribution
164+choose :: (FLN () a) => Prob -> Dist a
165+choose prob = D (col [prob, 1 - prob])
166+
167+-- | Creates a distribution given a shape function
168+shape :: (FLN () a) => (Prob -> Prob) -> [a] -> Dist a
169+shape _ [] = error "Probability.shape: empty list"
170+shape f xs =
171+ let incr = 1 / fromIntegral (length xs - 1)
172+ ps = map f (iterate (+incr) 0)
173+ in fromFreqs (zip xs ps)
174+
175+-- | Constructs a Linear distribution
176+linear :: (FLN () a) => [a] -> Dist a
177+linear = shape id
178+
179+-- | Constructs an Uniform distribution
180+uniform :: (FLN () a) => [a] -> Dist a
181+uniform = shape (const 1)
182+
183+-- | Constructs an Negative Exponential distribution
184+negExp :: (FLN () a) => [a] -> Dist a
185+negExp = shape (\x -> exp (-x))
186+
187+-- | Constructs an Normal distribution
188+normal :: (FLN () a) => [a] -> Dist a
189+normal = shape (normalCurve 0.5 0.5)
190+
191+-- | Transforms a 'Dist' into a list of pairs.
192+toValues :: forall a . (Enum a, Countable a, FLN () a) => Dist a -> [(a, Prob)]
193+toValues (D d) =
194+ let rows = fromInteger (natVal (Proxy :: Proxy (Count a)))
195+ probs = toList d
196+ res = zip (map toEnum [0..rows]) probs
197+ in res
198+
199+-- | Pretty a distribution
200+prettyDist :: forall a. (Show a, Enum a, Countable a, FLN () a) => Dist a -> String
201+prettyDist d =
202+ let values = sortBy (\(a, p1) (b, p2) -> compare p2 p1) (toValues @a d)
203+ w = maximum (map (length . show . fst) values)
204+ in concatMap
205+ (\(x,p) -> showR w x ++ ' ': showProb p ++ "\n")
206+ values
207+ where
208+ showProb p = show (p * 100) ++ "%"
209+ showR n x = show x ++ " "
210+
211+-- | Pretty Print a distribution
212+prettyPrintDist :: forall a . (Show a, Enum a, Countable a, FLN () a) => Dist a -> IO ()
213+prettyPrintDist = putStrLn . prettyDist @a
214+
215+-- Auxiliary functions
216+
217+fromFreqs :: (FLN () a) => [(a,Prob)] -> Dist a
218+fromFreqs xs = D (col (map (\(x,p) -> p/q) xs))
219+ where q = sum $ map snd xs
220+
221+normalCurve :: Prob -> Prob -> Prob -> Prob
222+normalCurve mean dev x =
223+ let u = (x - mean) / dev
224+ in exp (-1/2 * u^(2::Int)) / sqrt (2 * pi)
src/LAoP/Matrix/Internal.hsnew file+977
@@ -0,0 +1,977 @@
1+{-# LANGUAGE StrictData #-}
2+{-# LANGUAGE TypeFamilyDependencies #-}
3+{-# LANGUAGE ConstraintKinds #-}
4+{-# LANGUAGE AllowAmbiguousTypes #-}
5+{-# LANGUAGE DataKinds #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE GADTs #-}
9+{-# LANGUAGE InstanceSigs #-}
10+{-# LANGUAGE MultiParamTypeClasses #-}
11+{-# LANGUAGE NoStarIsType #-}
12+{-# LANGUAGE ScopedTypeVariables #-}
13+{-# LANGUAGE StandaloneDeriving #-}
14+{-# LANGUAGE TypeApplications #-}
15+{-# LANGUAGE TypeOperators #-}
16+{-# LANGUAGE UndecidableInstances #-}
17+
18+-----------------------------------------------------------------------------
19+-- |
20+-- Module : LAoP.Matrix.Internal
21+-- Copyright : (c) Armando Santos 2019-2020
22+-- Maintainer : armandoifsantos@gmail.com
23+-- Stability : experimental
24+--
25+-- The LAoP discipline generalises relations and functions treating them as
26+-- Boolean matrices and in turn consider these as arrows.
27+--
28+-- __LAoP__ is a library for algebraic (inductive) construction and manipulation of matrices
29+-- in Haskell. See <https://github.com/bolt12/master-thesis my Msc Thesis> for the
30+-- motivation behind the library, the underlying theory, and implementation details.
31+--
32+-- This module offers many of the combinators mentioned in the work of
33+-- Macedo (2012) and Oliveira (2012).
34+--
35+-- This is an Internal module and it is no supposed to be imported.
36+--
37+-----------------------------------------------------------------------------
38+
39+module LAoP.Matrix.Internal
40+ ( -- | This definition makes use of the fact that 'Void' is
41+ -- isomorphic to 0 and '()' to 1 and captures matrix
42+ -- dimensions as stacks of 'Either's.
43+ --
44+ -- There exists two type families that make it easier to write
45+ -- matrix dimensions: 'FromNat' and 'Count'. This approach
46+ -- leads to a very straightforward implementation
47+ -- of LAoP combinators.
48+
49+ -- * Type safe matrix representation
50+ Matrix (..),
51+
52+ -- * Constraint type aliases
53+ Countable,
54+ CountableDims,
55+ CountableN,
56+ CountableDimsN,
57+ FL,
58+ FLN,
59+ Liftable,
60+ Trivial,
61+
62+ -- * Primitives
63+ one,
64+ join,
65+ fork,
66+
67+ -- * Auxiliary type families
68+ FromNat,
69+ Count,
70+ Normalize,
71+
72+ -- * Matrix construction and conversion
73+ FromLists,
74+ fromLists,
75+ toLists,
76+ toList,
77+ matrixBuilder,
78+ matrixBuilder',
79+ row,
80+ col,
81+ zeros,
82+ ones,
83+ bang,
84+ constant,
85+
86+ -- * Misc
87+ -- ** Get dimensions
88+ columns,
89+ columns',
90+ rows,
91+ rows',
92+
93+ -- ** Matrix Transposition
94+ tr,
95+
96+ -- ** Scalar multiplication/division of matrices
97+ (.|),
98+ (./),
99+
100+ -- ** Selective operator
101+ select,
102+ branch,
103+
104+ -- ** McCarthy's Conditional
105+ cond,
106+
107+ -- ** Matrix "abiding"
108+ abideJF,
109+ abideFJ,
110+
111+ -- ** Zip matrices
112+ zipWithM,
113+
114+ -- * Biproduct approach
115+ -- ** Fork
116+ (===),
117+ -- *** Projections
118+ p1,
119+ p2,
120+ -- ** Join
121+ (|||),
122+ -- *** Injections
123+ i1,
124+ i2,
125+ -- ** Bifunctors
126+ (-|-),
127+ (><),
128+
129+ -- ** Applicative matrix combinators
130+
131+ -- | Note that given the restrictions imposed it is not possible to
132+ -- implement the standard type classes present in standard Haskell.
133+
134+ -- *** Matrix pairing projections
135+ fstM,
136+ sndM,
137+
138+ -- *** Matrix pairing
139+ kr,
140+
141+ -- * Matrix composition and lifting
142+
143+ -- ** Arrow matrix combinators
144+
145+ -- | Note that given the restrictions imposed it is not possible to
146+ -- implement the standard type classes present in standard Haskell.
147+ iden,
148+ comp,
149+ fromF',
150+ fromF,
151+
152+ -- * Matrix printing
153+ pretty,
154+ prettyPrint,
155+
156+ -- * Other
157+ toBool,
158+ fromBool,
159+ compRel,
160+ divR,
161+ divL,
162+ divS,
163+ fromFRel,
164+ fromFRel',
165+ toRel,
166+ negateM,
167+ orM,
168+ andM,
169+ subM
170+ )
171+ where
172+
173+import LAoP.Utils.Internal
174+import Data.Bool
175+import Data.Kind
176+import Data.List
177+import Data.Maybe
178+import Data.Proxy
179+import Data.Typeable
180+import Data.Void
181+import GHC.TypeLits
182+import Data.Type.Equality
183+import GHC.Generics
184+import Control.DeepSeq
185+import Prelude hiding (id, (.))
186+import qualified Prelude (id, (.))
187+
188+-- | LAoP (Linear Algebra of Programming) Inductive Matrix definition.
189+data Matrix e cols rows where
190+ One :: e -> Matrix e () ()
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)
193+
194+deriving instance (Show e) => Show (Matrix e cols rows)
195+
196+-- | Type family that computes the cardinality of a given type dimension.
197+--
198+-- It can also count the cardinality of custom types that implement the
199+-- 'Generic' instance.
200+type family Count (d :: Type) :: Nat where
201+ Count (Natural n m) = (m - n) + 1
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)
206+ -- Generics
207+ Count (M1 _ _ f p) = Count (f p)
208+ Count (K1 _ _ _) = 1
209+ Count (V1 _) = 0
210+ Count (U1 _) = 1
211+ Count ((:*:) a b p) = Count (a p) * Count (b p)
212+ Count ((:+:) a b p) = Count (a p) + Count (b p)
213+ Count d = Count (Rep d R)
214+
215+-- | Type family that computes of a given type dimension from a given natural
216+--
217+-- Thanks to Li-Yao Xia this type family is super fast.
218+type family FromNat (n :: Nat) :: Type where
219+ FromNat 1 = ()
220+ FromNat n = FromNat' (Mod n 2 == 0) (FromNat (Div n 2))
221+
222+type family FromNat' (b :: Bool) (m :: Type) :: Type where
223+ FromNat' 'True m = Either m m
224+ FromNat' 'False m = Either () (Either m m)
225+
226+-- | Type family that normalizes the representation of a given data
227+-- structure
228+type family Normalize (d :: Type) :: Type where
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.
244+instance (Num e) => Category (Matrix e) where
245+ type Object (Matrix e) a = (FL a a, Countable a)
246+ id = iden
247+ (.) = comp
248+
249+instance NFData e => NFData (Matrix e cols rows) where
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
253+
254+instance Eq e => Eq (Matrix e cols rows) where
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
260+
261+instance Num e => Num (Matrix e cols rows) where
262+ a + b = zipWithM (+) a b
263+
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)
275+
276+instance Ord e => Ord (Matrix e cols rows) where
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
282+
283+-- Primitives
284+
285+-- | Unit matrix constructor
286+one :: e -> Matrix e () ()
287+one = One
288+
289+-- | Matrix 'Join' constructor
290+join :: Matrix e a rows -> Matrix e b rows -> Matrix e (Either a b) rows
291+join = Join
292+
293+infixl 3 |||
294+
295+-- | Matrix 'Join' constructor
296+(|||) :: Matrix e a rows -> Matrix e b rows -> Matrix e (Either a b) rows
297+(|||) = Join
298+
299+-- | Matrix 'Fork' constructor
300+fork :: Matrix e cols a -> Matrix e cols b -> Matrix e cols (Either a b)
301+fork = Fork
302+
303+infixl 2 ===
304+
305+-- | Matrix 'Fork' constructor
306+(===) :: Matrix e cols a -> Matrix e cols b -> Matrix e cols (Either a b)
307+(===) = Fork
308+
309+-- Construction
310+
311+-- | Type class for defining the 'fromList' conversion function.
312+--
313+-- Given that it is not possible to branch on types at the term level type
314+-- classes are needed very much like an inductive definition but on types.
315+class FromLists cols rows where
316+ -- | Build a matrix out of a list of list of elements. Throws a runtime
317+ -- error if the dimensions do not match.
318+ fromLists :: [[e]] -> Matrix e cols rows
319+
320+instance FromLists () () where
321+ fromLists [[e]] = One e
322+ fromLists _ = error "Wrong dimensions"
323+
324+instance (FromLists cols ()) => FromLists (Either () cols) () where
325+ fromLists [h : t] = Join (One h) (fromLists [t])
326+ fromLists _ = error "Wrong dimensions"
327+
328+instance {-# OVERLAPPABLE #-}
329+ (FromLists a (), FromLists b (), Countable a) => FromLists (Either a b) () where
330+ fromLists [l] =
331+ let rowsA = fromInteger (natVal (Proxy :: Proxy (Count a)))
332+ in Join (fromLists [take rowsA l]) (fromLists [drop rowsA l])
333+ fromLists _ = error "Wrong dimensions"
334+
335+instance (FromLists () rows) => FromLists () (Either () rows) where
336+ fromLists ([h] : t) = Fork (One h) (fromLists t)
337+ fromLists _ = error "Wrong dimensions"
338+
339+instance {-# OVERLAPPABLE #-}
340+ (FromLists () a, FromLists () b, Countable a) => FromLists () (Either a b) where
341+ fromLists l@([_] : _) =
342+ let rowsA = fromInteger (natVal (Proxy :: Proxy (Count a)))
343+ in Fork (fromLists (take rowsA l)) (fromLists (drop rowsA l))
344+ fromLists _ = error "Wrong dimensions"
345+
346+instance (FromLists (Either a b) c, FromLists (Either a b) d, Countable c)
347+ => FromLists (Either a b) (Either c d) where
348+ fromLists l@(h : t) =
349+ let lh = length h
350+ rowsC = fromInteger (natVal (Proxy :: Proxy (Count c)))
351+ condition = all ((== lh) . length) t
352+ in if lh > 0 && condition
353+ then Fork (fromLists (take rowsC l)) (fromLists (drop rowsC l))
354+ else error "Not all rows have the same length"
355+
356+-- | Matrix builder function. Constructs a matrix provided with
357+-- a construction function that operates with indices.
358+matrixBuilder' ::
359+ forall e cols rows.
360+ ( FL cols rows,
361+ CountableDims cols rows
362+ ) => ((Int, Int) -> e) -> Matrix e cols rows
363+matrixBuilder' f =
364+ let c = fromInteger $ natVal (Proxy :: Proxy (Count cols))
365+ r = fromInteger $ natVal (Proxy :: Proxy (Count rows))
366+ positions = [(a, b) | a <- [0 .. (r - 1)], b <- [0 .. (c - 1)]]
367+ in fromLists . map (map f) . groupBy (\(x, _) (w, _) -> x == w) $ positions
368+
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+
389+-- | Constructs a column vector matrix
390+col :: (FL () rows) => [e] -> Matrix e () rows
391+col = fromLists . map (: [])
392+
393+-- | Constructs a row vector matrix
394+row :: (FL cols ()) => [e] -> Matrix e cols ()
395+row = fromLists . (: [])
396+
397+-- | Lifts functions to matrices with arbitrary dimensions.
398+--
399+-- NOTE: Be careful to not ask for a matrix bigger than the cardinality of
400+-- types @a@ or @b@ allows.
401+fromF' ::
402+ forall a b cols rows e.
403+ ( Liftable e a b,
404+ CountableDims cols rows,
405+ FL rows cols
406+ ) =>
407+ (a -> b) ->
408+ Matrix e cols rows
409+fromF' f =
410+ let minA = minBound @a
411+ maxA = maxBound @a
412+ minB = minBound @b
413+ maxB = maxBound @b
414+ ccols = fromInteger $ natVal (Proxy :: Proxy (Count cols))
415+ rrows = fromInteger $ natVal (Proxy :: Proxy (Count rows))
416+ elementsA = take ccols [minA .. maxA]
417+ elementsB = take rrows [minB .. maxB]
418+ combinations = (,) <$> elementsA <*> elementsB
419+ combAp = map snd . sort . map (\(a, b) -> if f a == b
420+ then ((fromEnum a, fromEnum b), 1)
421+ else ((fromEnum a, fromEnum b), 0)) $ combinations
422+ mList = buildList combAp rrows
423+ in tr $ fromLists mList
424+ where
425+ buildList [] _ = []
426+ buildList l r = take r l : buildList (drop r l) r
427+
428+-- | Lifts functions to matrices with dimensions matching @a@ and @b@
429+-- cardinality's.
430+fromF ::
431+ forall a b e.
432+ ( Liftable e a b,
433+ CountableDimsN a b,
434+ FLN b a
435+ ) =>
436+ (a -> b) ->
437+ Matrix e (Normalize a) (Normalize b)
438+fromF = fromF'
439+
440+-- Conversion
441+
442+-- | Converts a matrix to a list of lists of elements.
443+toLists :: Matrix e cols rows -> [[e]]
444+toLists (One e) = [[e]]
445+toLists (Fork l r) = toLists l ++ toLists r
446+toLists (Join l r) = zipWith (++) (toLists l) (toLists r)
447+
448+-- | Converts a matrix to a list of elements.
449+toList :: Matrix e cols rows -> [e]
450+toList = concat . toLists
451+
452+-- Zeros Matrix
453+
454+-- | The zero matrix. A matrix wholly filled with zeros.
455+zeros :: (Num e, FL cols rows, CountableDims cols rows) => Matrix e cols rows
456+zeros = matrixBuilder' (const 0)
457+
458+-- Ones Matrix
459+
460+-- | The ones matrix. A matrix wholly filled with ones.
461+--
462+-- Also known as T (Top) matrix.
463+ones :: (Num e, FL cols rows, CountableDims cols rows) => Matrix e cols rows
464+ones = matrixBuilder' (const 1)
465+
466+-- Const Matrix
467+
468+-- | The constant matrix constructor. A matrix wholly filled with a given
469+-- value.
470+constant :: (Num e, FL cols rows, CountableDims cols rows) => e -> Matrix e cols rows
471+constant e = matrixBuilder' (const e)
472+
473+-- Bang Matrix
474+
475+-- | The T (Top) row vector matrix.
476+bang :: forall e cols. (Num e, Enum e, FL cols (), Countable cols) => Matrix e cols ()
477+bang =
478+ let c = fromInteger $ natVal (Proxy :: Proxy (Count cols))
479+ in fromLists [take c [1, 1 ..]]
480+
481+-- iden Matrix
482+
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 #-}
487+
488+-- Matrix composition (MMM)
489+
490+-- | Matrix composition. Equivalent to matrix-matrix multiplication.
491+--
492+-- This definition takes advantage of divide-and-conquer and fusion laws
493+-- from LAoP.
494+comp :: (Num e) => Matrix e cr rows -> Matrix e cols cr -> Matrix e cols rows
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)
522+
523+-- Projections
524+
525+-- | Biproduct first component projection
526+p1 :: (Num e, CountableDims n m, FL n m, FL m m) => Matrix e (Either m n) m
527+p1 = join id zeros
528+
529+-- | Biproduct second component projection
530+p2 :: (Num e, CountableDims n m, FL m n, FL n n) => Matrix e (Either m n) n
531+p2 = join zeros id
532+
533+-- Injections
534+
535+-- | Biproduct first component injection
536+i1 :: (Num e, CountableDims n m, FL n m, FL m m) => Matrix e m (Either m n)
537+i1 = tr p1
538+
539+-- | Biproduct second component injection
540+i2 :: (Num e, CountableDims n m, FL m n, FL n n) => Matrix e n (Either m n)
541+i2 = tr p2
542+
543+-- Dimensions
544+
545+-- | Obtain the number of rows.
546+--
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
551+rows _ = fromInteger $ natVal (Proxy :: Proxy (Count rows))
552+
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+
562+-- | Obtain the number of columns.
563+--
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
568+columns _ = fromInteger $ natVal (Proxy :: Proxy (Count cols))
569+
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+
579+-- Coproduct Bifunctor
580+
581+infixl 5 -|-
582+
583+-- | Matrix coproduct functor also known as matrix direct sum.
584+(-|-) ::
585+ forall e n k m j.
586+ ( Num e,
587+ CountableDims j k,
588+ FL k k,
589+ FL j k,
590+ FL k j,
591+ FL j j
592+ ) =>
593+ Matrix e n k ->
594+ Matrix e m j ->
595+ Matrix e (Either n m) (Either k j)
596+(-|-) a b = Join (i1 . a) (i2 . b)
597+
598+-- Khatri Rao Product and projections
599+
600+-- | Khatri Rao product first component projection matrix.
601+fstM ::
602+ forall e m k .
603+ ( Num e,
604+ CountableDims k m,
605+ FL (Normalize (m, k)) m,
606+ CountableN (m, k)
607+ ) => Matrix e (Normalize (m, k)) m
608+fstM = matrixBuilder' f
609+ where
610+ offset = fromInteger (natVal (Proxy :: Proxy (Count k)))
611+ f (x, y)
612+ | y >= (x * offset) && y <= (x * offset + offset - 1) = 1
613+ | otherwise = 0
614+
615+-- | Khatri Rao product second component projection matrix.
616+sndM ::
617+ forall e m k .
618+ ( Num e,
619+ CountableDims k m,
620+ FL (Normalize (m, k)) k,
621+ CountableN (m, k)
622+ ) => Matrix e (Normalize (m, k)) k
623+sndM = matrixBuilder' f
624+ where
625+ offset = fromInteger (natVal (Proxy :: Proxy (Count k)))
626+ f (x, y)
627+ | x == y || mod (y - x) offset == 0 = 1
628+ | otherwise = 0
629+
630+-- | Khatri Rao Matrix product also known as matrix pairing.
631+--
632+-- NOTE: That this is not a true categorical product, see for instance:
633+--
634+-- @
635+-- | fstM . kr a b == a
636+-- kr a b ==> |
637+-- | sndM . kr a b == b
638+-- @
639+--
640+-- __Emphasis__ on the implication symbol.
641+kr ::
642+ forall e cols a b.
643+ ( Num e,
644+ CountableDims a b,
645+ CountableN (a, b),
646+ FL (Normalize (a, b)) a,
647+ FL (Normalize (a, b)) b
648+ ) => Matrix e cols a -> Matrix e cols b -> Matrix e cols (Normalize (a, 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)
653+
654+-- Product Bifunctor (Kronecker)
655+
656+infixl 4 ><
657+
658+-- | Matrix product functor also known as kronecker product
659+(><) ::
660+ forall e m p n q.
661+ ( Num e,
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+ )
670+ => Matrix e m p -> Matrix e n q -> Matrix e (Normalize (m, n)) (Normalize (p, q))
671+(><) a b =
672+ let fstM' = fstM @e @m @n
673+ sndM' = sndM @e @m @n
674+ in kr (a . fstM') (b . sndM')
675+
676+-- Matrix abide Join Fork
677+
678+-- | Matrix "abiding" following the 'Join'-'Fork' exchange law.
679+--
680+-- Law:
681+--
682+-- @
683+-- 'Join' ('Fork' a c) ('Fork' b d) == 'Fork' ('Join' a b) ('Join' c d)
684+-- @
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)
690+
691+-- Matrix abide Fork Join
692+
693+-- | Matrix "abiding" followin the 'Fork'-'Join' abide law.
694+--
695+-- @
696+-- 'Fork' ('Join' a b) ('Join' c d) == 'Join' ('Fork' a c) ('Fork' b d)
697+-- @
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)
703+
704+-- Matrix transposition
705+
706+-- | Matrix transposition.
707+tr :: Matrix e cols rows -> Matrix e rows cols
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)
711+
712+-- Selective 'select' operator
713+
714+-- | Selective functors 'select' operator equivalent inspired by the
715+-- ArrowMonad solution presented in the paper.
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
743+
744+-- McCarthy's Conditional
745+
746+-- | McCarthy's Conditional expresses probabilistic choice.
747+cond ::
748+ ( Trivial cols,
749+ Countable cols,
750+ FL () cols,
751+ FL cols (),
752+ FL cols cols,
753+ Bounded a,
754+ Enum a,
755+ Num e,
756+ Ord e
757+ )
758+ =>
759+ (a -> Bool) -> Matrix e cols rows -> Matrix e cols rows -> Matrix e cols rows
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,
768+ Bounded a,
769+ Enum a,
770+ Num e,
771+ Ord e
772+ )
773+ =>
774+ (a -> Bool) -> Matrix e q (Either q q)
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+ )
786+ => (a -> Bool) -> Matrix e q q
787+corr p = let f = fromF' p :: Matrix e q ()
788+ in kr f (id :: Matrix e q q)
789+
790+-- Pretty print
791+
792+prettyAux :: Show e => [[e]] -> [[e]] -> String
793+prettyAux [] _ = ""
794+prettyAux [[e]] m = "│ " ++ fill (show e) ++ " │\n"
795+ where
796+ v = fmap show m
797+ widest = maximum $ fmap length v
798+ fill str = replicate (widest - length str - 2) ' ' ++ str
799+prettyAux [h] m = "│ " ++ fill (unwords $ map show h) ++ " │\n"
800+ where
801+ v = fmap show m
802+ widest = maximum $ fmap length v
803+ fill str = replicate (widest - length str - 2) ' ' ++ str
804+prettyAux (h : t) l = "│ " ++ fill (unwords $ map show h) ++ " │\n" ++
805+ prettyAux t l
806+ where
807+ v = fmap show l
808+ widest = maximum $ fmap length v
809+ fill str = replicate (widest - length str - 2) ' ' ++ str
810+
811+-- | Matrix pretty printer
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
822+ fill str = replicate (widest - length str) ' ' ++ str
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)
839+
840+-- | Matrix pretty printer
841+prettyPrint :: (CountableDims cols rows, Show e) => Matrix e cols rows -> IO ()
842+prettyPrint = putStrLn . pretty
843+
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+
852+-- Relational operators functions
853+
854+type Boolean = Natural 0 1
855+type Relation a b = Matrix Boolean a b
856+
857+-- | Helper conversion function
858+toBool :: (Num e, Eq e) => e -> Bool
859+toBool n
860+ | n == 0 = False
861+ | n == 1 = True
862+
863+-- | Helper conversion function
864+fromBool :: Bool -> Natural 0 1
865+fromBool True = nat 1
866+fromBool False = nat 0
867+
868+-- | Relational negation
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)
873+
874+-- | Relational addition
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
881+
882+-- | Relational multiplication
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
889+
890+-- | Relational subtraction
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
897+
898+-- | Matrix relational composition.
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
921+
922+-- | Lifts functions to relations with arbitrary dimensions.
923+--
924+-- NOTE: Be careful to not ask for a relation bigger than the cardinality of
925+-- types @a@ or @b@ allows.
926+fromFRel' ::
927+ forall a b cols rows.
928+ ( Liftable Boolean a b,
929+ CountableDims cols rows,
930+ FL rows cols
931+ ) =>
932+ (a -> b) ->
933+ Relation cols rows
934+fromFRel' = fromF'
935+
936+-- | Lifts functions to relations with dimensions matching @a@ and @b@
937+-- cardinality's.
938+fromFRel ::
939+ forall a b.
940+ ( Liftable Boolean a b,
941+ CountableDimsN a b,
942+ FLN b a
943+ ) =>
944+ (a -> b) ->
945+ Relation (Normalize a) (Normalize b)
946+fromFRel = fromFRel'
947+
948+-- | Lifts a relation function to a Boolean Matrix
949+toRel ::
950+ forall a b.
951+ ( Bounded a,
952+ Bounded b,
953+ Enum a,
954+ Enum b,
955+ Eq b,
956+ CountableDims a b,
957+ FLN b a
958+ )
959+ => (a -> b -> Bool) -> Relation (Normalize a) (Normalize b)
960+toRel f =
961+ let minA = minBound @a
962+ maxA = maxBound @a
963+ minB = minBound @b
964+ maxB = maxBound @b
965+ ccols = fromInteger $ natVal (Proxy :: Proxy (Count a))
966+ rrows = fromInteger $ natVal (Proxy :: Proxy (Count b))
967+ elementsA = take ccols [minA .. maxA]
968+ elementsB = take rrows [minB .. maxB]
969+ combinations = (,) <$> elementsA <*> elementsB
970+ combAp = map snd . sort . map (\(a, b) -> if uncurry f (a, b)
971+ then ((fromEnum a, fromEnum b), nat 1)
972+ else ((fromEnum a, fromEnum b), nat 0)) $ combinations
973+ mList = buildList combAp rrows
974+ in tr $ fromLists mList
975+ where
976+ buildList [] _ = []
977+ buildList l r = take r l : buildList (drop r l) r
src/LAoP/Matrix/Nat.hsnew file+490
@@ -0,0 +1,490 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE AllowAmbiguousTypes #-}
3+{-# LANGUAGE DataKinds #-}
4+{-# LANGUAGE DerivingVia #-}
5+{-# LANGUAGE FlexibleContexts #-}
6+{-# LANGUAGE FlexibleInstances #-}
7+{-# LANGUAGE GADTs #-}
8+{-# LANGUAGE KindSignatures #-}
9+{-# LANGUAGE MultiParamTypeClasses #-}
10+{-# LANGUAGE NoStarIsType #-}
11+{-# LANGUAGE RankNTypes #-}
12+{-# LANGUAGE ScopedTypeVariables #-}
13+{-# LANGUAGE TypeApplications #-}
14+{-# LANGUAGE TypeOperators #-}
15+{-# LANGUAGE UndecidableInstances #-}
16+
17+-----------------------------------------------------------------------------
18+-- |
19+-- Module : LAoP.Matrix.Nat
20+-- Copyright : (c) Armando Santos 2019-2020
21+-- Maintainer : armandoifsantos@gmail.com
22+-- Stability : experimental
23+--
24+-- The LAoP discipline generalises relations and functions treating them as
25+-- Boolean matrices and in turn consider these as arrows.
26+--
27+-- __LAoP__ is a library for algebraic (inductive) construction and manipulation of matrices
28+-- in Haskell. See <https://github.com/bolt12/master-thesis my Msc Thesis> for the
29+-- motivation behind the library, the underlying theory, and implementation details.
30+--
31+-- This module offers a newtype wrapper around 'Matrix.Type.Matrix' that
32+-- uses type level naturals instead of standard data types for the matrices
33+-- dimensions.
34+--
35+-----------------------------------------------------------------------------
36+
37+module LAoP.Matrix.Nat
38+ ( -- | LAoP (Linear Algebra of Programming) Inductive Matrix definition.
39+ --
40+ -- LAoP generalises relations and functions treating them as
41+ -- Boolean matrices and in turn consider these as arrows.
42+ -- This library offers many of the combinators mentioned in the work of
43+ -- Macedo (2012) and Oliveira (2012).
44+ --
45+ -- This definition is a wrapper around 'Matrix.Type' but
46+ -- dimensions are type level Naturals. Type inference might not
47+ -- be as desired.
48+ --
49+ -- There exists two type families that make it easier to write
50+ -- matrix dimensions: 'FromNat' and 'Count'. This approach
51+ -- leads to a very straightforward implementation
52+ -- of LAoP combinators.
53+
54+ -- * Type safe matrix representation
55+ Matrix (..),
56+
57+ -- * Constraint type synonyms
58+ Countable,
59+ CountableDims,
60+ CountableN,
61+ CountableNz,
62+ CountableDimsN,
63+ FLN,
64+ FLNz,
65+ Liftable,
66+ TrivialE,
67+ TrivialP,
68+
69+ -- * Primitives
70+ one,
71+ join,
72+ fork,
73+
74+ -- * Auxiliary type families
75+ I.FromNat,
76+ I.Count,
77+ I.Normalize,
78+
79+ -- * Matrix construction and conversion
80+ I.FL,
81+ fromLists,
82+ toLists,
83+ toList,
84+ matrixBuilder',
85+ row,
86+ col,
87+ zeros,
88+ ones,
89+ bang,
90+ constant,
91+
92+ -- * Misc
93+ -- ** Get dimensions
94+ columns,
95+ rows,
96+
97+ -- ** Matrix Transposition
98+ tr,
99+
100+ -- ** Scalar multiplication/division of matrices
101+ (.|),
102+ (./),
103+
104+ -- ** Selective operator
105+ select,
106+
107+ -- ** McCarthy's Conditional
108+ cond,
109+
110+ -- ** Matrix "abiding"
111+ abideJF,
112+ abideFJ,
113+
114+ -- ** Zip Matrices
115+ zipWithM,
116+
117+ -- * Biproduct approach
118+ -- ** Fork
119+ (===),
120+ -- *** Projections
121+ p1,
122+ p2,
123+ -- ** Join
124+ (|||),
125+ -- *** Injections
126+ i1,
127+ i2,
128+ -- ** Bifunctors
129+ (-|-),
130+ (><),
131+
132+ -- ** Applicative matrix combinators
133+
134+ -- | Note that given the restrictions imposed it is not possible to
135+ -- implement the standard type classes present in standard Haskell.
136+ -- *** Matrix pairing projections
137+ fstM,
138+ sndM,
139+
140+ -- *** Matrix pairing
141+ kr,
142+
143+ -- * Matrix composition and lifting
144+
145+ -- ** Arrow matrix combinators
146+
147+ -- | Note that given the restrictions imposed it is not possible to
148+ -- implement the standard type classes present in standard Haskell.
149+ iden,
150+ comp,
151+ fromF',
152+ fromF,
153+
154+ -- * Matrix printing
155+ pretty,
156+ prettyPrint
157+ )
158+where
159+
160+import Data.Proxy
161+import GHC.TypeLits
162+import Control.DeepSeq
163+import qualified LAoP.Matrix.Internal as I
164+
165+newtype Matrix e (cols :: Nat) (rows :: Nat) = M (I.Matrix e (I.FromNat cols) (I.FromNat rows))
166+ deriving (Show, Num, Eq, Ord, NFData) via (I.Matrix e (I.FromNat cols) (I.FromNat rows))
167+
168+-- | Constraint type synonyms to keep the type signatures less convoluted
169+type Countable a = KnownNat (I.Count a)
170+type CountableDims a b = (Countable a, Countable b)
171+type CountableN a = KnownNat (I.Count (I.FromNat a))
172+type CountableNz a = KnownNat (I.Count (I.Normalize a))
173+type CountableDimsN a b = (CountableN a, CountableN b)
174+type FLN e a b = I.FL (I.FromNat a) (I.FromNat b)
175+type FLNz e a b = I.FL (I.Normalize a) (I.Normalize b)
176+type Liftable e a b = (Bounded a, Bounded b, Enum a, Enum b, Eq b, Num e, Ord e)
177+type TrivialE a b = I.FromNat (a + b) ~ Either (I.FromNat a) (I.FromNat b)
178+type TrivialP a b = I.FromNat (a * b) ~ I.FromNat (I.Count (I.FromNat a) * I.Count (I.FromNat b))
179+
180+-- Primitives
181+
182+one :: e -> Matrix e 1 1
183+one = M . I.One
184+
185+join ::
186+ (TrivialE a b) =>
187+ Matrix e a rows ->
188+ Matrix e b rows ->
189+ Matrix e (a + b) rows
190+join (M a) (M b) = M (I.Join a b)
191+
192+infixl 3 |||
193+(|||) ::
194+ (TrivialE a b) =>
195+ Matrix e a rows ->
196+ Matrix e b rows ->
197+ Matrix e (a + b) rows
198+(|||) = join
199+
200+fork ::
201+ (TrivialE a b) =>
202+ Matrix e cols a ->
203+ Matrix e cols b ->
204+ Matrix e cols (a + b)
205+fork (M a) (M b) = M (I.Fork a b)
206+
207+infixl 2 ===
208+(===) ::
209+ (TrivialE a b) =>
210+ Matrix e cols a ->
211+ Matrix e cols b ->
212+ Matrix e cols (a + b)
213+(===) = fork
214+
215+-- Construction
216+
217+fromLists :: (FLN e cols rows) => [[e]] -> Matrix e cols rows
218+fromLists = M . I.fromLists
219+
220+-- | Matrix builder function. Constructs a matrix provided with
221+-- a construction function that operates with indices.
222+matrixBuilder' ::
223+ (FLN e cols rows, CountableN cols, CountableN rows)
224+ => ((Int, Int) -> e) -> Matrix e cols rows
225+matrixBuilder' = M . I.matrixBuilder'
226+
227+col :: (I.FL () (I.FromNat rows)) => [e] -> Matrix e 1 rows
228+col = M . I.col
229+
230+row :: (I.FL (I.FromNat cols) ()) => [e] -> Matrix e cols 1
231+row = M . I.row
232+
233+fromF' ::
234+ ( Liftable e a b,
235+ CountableN cols,
236+ CountableN rows,
237+ FLN e rows cols
238+ ) =>
239+ (a -> b) ->
240+ Matrix e cols rows
241+fromF' = M . I.fromF'
242+
243+fromF ::
244+ ( Liftable e a b,
245+ CountableNz a,
246+ CountableNz b,
247+ FLNz e b a
248+ ) =>
249+ (a -> b) ->
250+ Matrix e (I.Count a) (I.Count b)
251+fromF = undefined -- M . I.fromF
252+
253+-- Conversion
254+
255+toLists :: Matrix e cols rows -> [[e]]
256+toLists (M m) = I.toLists m
257+
258+toList :: Matrix e cols rows -> [e]
259+toList (M m) = I.toList m
260+
261+-- Zeros Matrix
262+
263+zeros ::
264+ (Num e, FLN e cols rows, CountableN cols, CountableN rows) =>
265+ Matrix e cols rows
266+zeros = M I.zeros
267+
268+-- Ones Matrix
269+
270+ones ::
271+ (Num e, FLN e cols rows, CountableN cols, CountableN rows) =>
272+ Matrix e cols rows
273+ones = M I.ones
274+
275+-- Const Matrix
276+
277+constant ::
278+ (Num e, FLN e cols rows, CountableN cols, CountableN rows) =>
279+ e ->
280+ Matrix e cols rows
281+constant = M . I.constant
282+
283+-- Bang Matrix
284+
285+bang ::
286+ forall e cols.
287+ (Num e, Enum e, I.FL (I.FromNat cols) (), CountableN cols) =>
288+ Matrix e cols 1
289+bang = M I.bang
290+
291+-- iden Matrix
292+
293+iden ::
294+ (Num e, FLN e cols cols, CountableN cols) =>
295+ Matrix e cols cols
296+iden = M I.iden
297+
298+-- Matrix composition (MMM)
299+
300+comp :: (Num e) => Matrix e cr rows -> Matrix e cols cr -> Matrix e cols rows
301+comp (M a) (M b) = M (I.comp a b)
302+
303+-- Scalar multiplication of matrices
304+
305+infixl 7 .|
306+-- | Scalar multiplication of matrices.
307+(.|) :: Num e => e -> Matrix e cols rows -> Matrix e cols rows
308+(.|) e (M m) = M (e I..| m)
309+
310+-- Scalar division of matrices
311+
312+infixl 7 ./
313+-- | Scalar multiplication of matrices.
314+(./) :: Fractional e => Matrix e cols rows -> e -> Matrix e cols rows
315+(./) (M m) e = M (m I../ e)
316+
317+p1 ::
318+ ( Num e,
319+ CountableDimsN n m,
320+ FLN e n m,
321+ FLN e m m,
322+ TrivialE m n
323+ ) =>
324+ Matrix e (m + n) m
325+p1 = M I.p1
326+
327+p2 ::
328+ ( Num e,
329+ CountableDimsN n m,
330+ FLN e m n,
331+ FLN e n n,
332+ TrivialE m n
333+ ) =>
334+ Matrix e (m + n) n
335+p2 = M I.p2
336+
337+-- Injections
338+
339+i1 ::
340+ ( Num e,
341+ CountableDimsN n rows,
342+ FLN e n rows,
343+ FLN e rows rows,
344+ TrivialE rows n
345+ ) =>
346+ Matrix e rows (rows + n)
347+i1 = tr p1
348+
349+i2 ::
350+ ( Num e,
351+ CountableDimsN rows m,
352+ FLN e m rows,
353+ FLN e rows rows,
354+ TrivialE m rows
355+ ) =>
356+ Matrix e rows (m + rows)
357+i2 = tr p2
358+
359+-- Dimensions
360+
361+rows :: (CountableN rows) => Matrix e cols rows -> Int
362+rows (M m) = I.rows m
363+
364+columns :: (CountableN cols) => Matrix e cols rows -> Int
365+columns (M m) = I.columns m
366+
367+infixl 5 -|-
368+
369+-- | Coproduct Bifunctor (Direct sum)
370+(-|-) ::
371+ ( Num e,
372+ CountableDimsN j k,
373+ FLN e k k,
374+ FLN e j k,
375+ FLN e k j,
376+ FLN e j j,
377+ TrivialE n m,
378+ TrivialE k j
379+ ) =>
380+ Matrix e n k ->
381+ Matrix e m j ->
382+ Matrix e (n + m) (k + j)
383+(-|-) (M a) (M b) = M ((I.-|-) a b)
384+
385+-- | Khatri Rao Product first projection
386+fstM ::
387+ forall e m k .
388+ ( Num e,
389+ CountableDimsN m k,
390+ CountableN (m * k),
391+ FLN e (m * k) m,
392+ TrivialP m k
393+ ) => Matrix e (m * k) m
394+fstM = M (I.fstM @e @(I.FromNat m) @(I.FromNat k))
395+
396+-- | Khatri Rao Product second projection
397+sndM ::
398+ forall e m k.
399+ ( Num e,
400+ CountableDimsN k m,
401+ FLN e (m * k) k,
402+ CountableN (m * k),
403+ TrivialP m k
404+ ) => Matrix e (m * k) k
405+sndM = M (I.sndM @e @(I.FromNat m) @(I.FromNat k))
406+
407+-- | Khatri Rao Product
408+kr ::
409+ forall e cols a b.
410+ ( Num e,
411+ CountableDimsN a b,
412+ CountableN (a * b),
413+ FLN e (a * b) a,
414+ FLN e (a * b) b,
415+ TrivialP a b
416+ ) => Matrix e cols a -> Matrix e cols b -> Matrix e cols (a * b)
417+kr a b =
418+ let fstM' = fstM @e @a @b
419+ sndM' = sndM @e @a @b
420+ in comp (tr fstM') a * comp (tr sndM') b
421+
422+-- | Product Bifunctor (Kronecker)
423+infixl 4 ><
424+
425+(><) ::
426+ forall e m p n q.
427+ ( Num e,
428+ CountableDimsN m n,
429+ CountableDimsN p q,
430+ CountableDimsN (m * n) (p * q),
431+ FLN e (m * n) m,
432+ FLN e (m * n) n,
433+ FLN e (p * q) p,
434+ FLN e (p * q) q,
435+ TrivialP m n,
436+ TrivialP p q
437+ ) => Matrix e m p -> Matrix e n q -> Matrix e (m * n) (p * q)
438+(><) a b =
439+ let fstM' = fstM @e @m @n
440+ sndM' = sndM @e @m @n
441+ in kr (comp a fstM') (comp b sndM')
442+
443+-- | Matrix abide Join Fork
444+abideJF :: Matrix e cols rows -> Matrix e cols rows
445+abideJF (M m) = M (I.abideJF m)
446+
447+-- | Matrix abide Fork Join
448+abideFJ :: Matrix e cols rows -> Matrix e cols rows
449+abideFJ (M m) = M (I.abideFJ m)
450+
451+-- | Matrix transposition
452+tr :: Matrix e cols rows -> Matrix e rows cols
453+tr (M m) = M (I.tr m)
454+
455+-- Selective 'select' operator
456+select ::
457+ ( Num e,
458+ FLN e rows1 rows1,
459+ CountableN rows1,
460+ I.FromNat rows2 ~ I.FromNat rows1,
461+ I.FromNat cols1 ~ I.FromNat cols2,
462+ I.FromNat rows3 ~ Either (I.FromNat cols3) (I.FromNat rows1)
463+ ) => Matrix e cols1 rows3 -> Matrix e cols3 rows1 -> Matrix e cols2 rows2
464+select (M m) (M y) = M (I.select m y)
465+
466+-- McCarthy's Conditional
467+
468+cond ::
469+ ( I.FromNat (I.Count (I.FromNat cols)) ~ I.FromNat cols,
470+ CountableN cols,
471+ I.FL () (I.FromNat cols),
472+ I.FL (I.FromNat cols) (),
473+ FLN e cols cols,
474+ Liftable e a Bool
475+ )
476+ =>
477+ (a -> Bool) -> Matrix e cols rows -> Matrix e cols rows -> Matrix e cols rows
478+cond p (M a) (M b) = M (I.cond p a b)
479+
480+-- Pretty print
481+
482+pretty :: (CountableDimsN cols rows, Show e) => Matrix e cols rows -> String
483+pretty (M m) = I.pretty m
484+
485+prettyPrint :: (CountableDimsN cols rows, Show e) => Matrix e cols rows -> IO ()
486+prettyPrint (M m) = I.prettyPrint m
487+
488+-- | Zip two matrices with a given binary function
489+zipWithM :: (e -> f -> g) -> Matrix e cols rows -> Matrix f cols rows -> Matrix g cols rows
490+zipWithM f (M a) (M b) = M (I.zipWithM f a b)
src/LAoP/Matrix/Type.hsnew file+707
@@ -0,0 +1,707 @@
1+{-# LANGUAGE ConstraintKinds #-}
2+{-# LANGUAGE TypeFamilies #-}
3+{-# LANGUAGE AllowAmbiguousTypes #-}
4+{-# LANGUAGE DataKinds #-}
5+{-# LANGUAGE DerivingVia #-}
6+{-# LANGUAGE FlexibleContexts #-}
7+{-# LANGUAGE FlexibleInstances #-}
8+{-# LANGUAGE GADTs #-}
9+{-# LANGUAGE MultiParamTypeClasses #-}
10+{-# LANGUAGE NoStarIsType #-}
11+{-# LANGUAGE RankNTypes #-}
12+{-# LANGUAGE ScopedTypeVariables #-}
13+{-# LANGUAGE TypeApplications #-}
14+{-# LANGUAGE TypeOperators #-}
15+{-# LANGUAGE UndecidableInstances #-}
16+
17+-----------------------------------------------------------------------------
18+-- |
19+-- Module : LAoP.Matrix.Type
20+-- Copyright : (c) Armando Santos 2019-2020
21+-- Maintainer : armandoifsantos@gmail.com
22+-- Stability : experimental
23+--
24+-- The LAoP discipline generalises relations and functions treating them as
25+-- Boolean matrices and in turn consider these as arrows.
26+--
27+-- __LAoP__ is a library for algebraic (inductive) construction and manipulation of matrices
28+-- in Haskell. See <https://github.com/bolt12/master-thesis my Msc Thesis> for the
29+-- motivation behind the library, the underlying theory, and implementation details.
30+--
31+-- This module offers a newtype wrapper around 'Matrix.Type.Matrix' that
32+-- uses arbitrary types instead of canonical data types for the matrices
33+-- dimensions.
34+--
35+-- __NOTE__: If the types in the dimensions are custom they must need to
36+-- implement a 'Generic' instance.
37+--
38+-----------------------------------------------------------------------------
39+
40+module LAoP.Matrix.Type
41+ ( -- | LAoP (Linear Algebra of Programming) Inductive Matrix definition.
42+ --
43+ -- LAoP generalises relations and functions treating them as
44+ -- Boolean matrices and in turn consider these as arrows.
45+ -- This library offers many of the combinators mentioned in the work of
46+ -- Macedo (2012) and Oliveira (2012).
47+ --
48+ -- This definition is a wrapper around 'Matrix.Type' but
49+ -- dimensions are arbitrary data types. Type inference might not
50+ -- be as desired.
51+
52+ -- __NOTE__: If the types in the dimensions are custom they must need to
53+ -- implement a 'Generic' instance.
54+ --
55+
56+ -- * Type safe matrix representation
57+ Matrix (..),
58+
59+ -- * Constraint type aliases
60+ Countable,
61+ CountableDims,
62+ CountableN,
63+ CountableDimsN,
64+ FLN,
65+ Liftable,
66+ Trivial,
67+ TrivialP,
68+
69+ -- * Type aliases
70+ Zero,
71+ One,
72+
73+ -- * Primitives
74+ one,
75+ join,
76+ fork,
77+
78+ -- * Auxiliary type families
79+ I.FromNat,
80+ I.Count,
81+ I.Normalize,
82+
83+ -- * Matrix construction and conversion
84+ I.FromLists,
85+ fromLists,
86+ toLists,
87+ toList,
88+ matrixBuilder',
89+ matrixBuilder,
90+ row,
91+ col,
92+ zeros,
93+ ones,
94+ bang,
95+ point,
96+ constant,
97+
98+ -- * Functor instance equivalent function
99+ fmapM,
100+ bimapM,
101+
102+ -- * Applicative/Monoidal instance equivalent functions
103+ unitM,
104+ multM,
105+
106+ -- * Selective equivalent instance function
107+ selectM,
108+
109+ -- * Monad equivalent instance function
110+ returnM,
111+ bindM,
112+
113+ -- * Misc
114+ -- ** Get dimensions
115+ columns,
116+ columns',
117+ rows,
118+ rows',
119+
120+ -- ** Matrix Transposition
121+ tr,
122+
123+ -- ** Scalar multiplication/division of matrices
124+ (.|),
125+ (./),
126+
127+ -- ** McCarthy's Conditional
128+ cond,
129+
130+ -- ** Matrix "abiding"
131+ abideJF,
132+ abideFJ,
133+
134+ -- ** Zip Matrices
135+ zipWithM,
136+
137+ -- * Biproduct approach
138+ -- ** Fork
139+ (===),
140+ -- *** Projections
141+ p1,
142+ p2,
143+ -- ** Join
144+ (|||),
145+ -- *** Injections
146+ i1,
147+ i2,
148+ -- ** Bifunctors
149+ (-|-),
150+ (><),
151+
152+ -- ** Applicative matrix combinators
153+
154+ -- | Note that given the restrictions imposed it is not possible to
155+ -- implement the standard type classes present in standard Haskell.
156+ -- *** Matrix pairing projections
157+ fstM,
158+ sndM,
159+
160+ -- *** Matrix pairing
161+ kr,
162+
163+ -- * Matrix composition and lifting
164+
165+ -- ** Arrow matrix combinators
166+
167+ -- | Note that given the restrictions imposed it is not possible to
168+ -- implement the standard type classes present in standard Haskell.
169+ iden,
170+ comp,
171+ fromF',
172+ fromF,
173+
174+ -- * Relation
175+ toRel,
176+
177+ -- * Matrix printing
178+ pretty,
179+ prettyPrint
180+ )
181+where
182+
183+import Data.Void
184+import Data.Proxy
185+import Data.Kind
186+import GHC.TypeLits
187+import Control.DeepSeq
188+import LAoP.Utils
189+import qualified LAoP.Matrix.Internal as I
190+import Prelude hiding (id, (.))
191+
192+newtype Matrix e (cols :: Type) (rows :: Type) = M (I.Matrix e (I.Normalize cols) (I.Normalize rows))
193+ deriving (Show, Num, Eq, Ord, NFData) via (I.Matrix e (I.Normalize cols) (I.Normalize rows))
194+
195+-- | Constraint type synonyms to keep the type signatures less convoluted
196+type Countable a = KnownNat (I.Count a)
197+type CountableDims a b = (Countable a, Countable b)
198+type CountableN a = KnownNat (I.Count (I.Normalize a))
199+type CountableDimsN a b = (CountableN a, CountableN b)
200+type FLN a b = I.FromLists (I.Normalize a) (I.Normalize b)
201+type Liftable e a b = (Bounded a, Bounded b, Enum a, Enum b, Eq b, Num e, Ord e)
202+type Trivial a = I.Normalize (I.Normalize a) ~ I.Normalize (I.Normalize (I.Normalize a))
203+type Trivial2 a = I.Normalize a ~ I.Normalize (I.Normalize a)
204+type Trivial3 a = I.FromNat (I.Count (I.Normalize (I.Normalize a))) ~ I.Normalize (I.Normalize a)
205+type TrivialP a b = I.Normalize (a, b) ~ I.Normalize (I.Normalize a, I.Normalize b)
206+
207+-- | It is possible to implement a constrained version of the category type
208+-- class.
209+instance (Num e) => Category (Matrix e) where
210+ type Object (Matrix e) a = (FLN a a, CountableN a)
211+ id = iden
212+ (.) = comp
213+
214+-- | Bifunctor equivalent function
215+bimapM ::
216+ ( Liftable e a b,
217+ Liftable e c d,
218+ CountableDimsN a c,
219+ CountableDimsN b d,
220+ FLN d c,
221+ FLN b a
222+ ) => (a -> b) -> (c -> d) -> Matrix e a c -> Matrix e b d
223+bimapM f g m = fromF g . m . tr (fromF f)
224+
225+-- | Zero type alias
226+type Zero = Void
227+
228+-- | One type alias
229+type One = ()
230+
231+-- Primitives
232+
233+-- | Unit matrix constructor
234+one :: e -> Matrix e One One
235+one = M . I.One
236+
237+-- | Matrix 'Join' constructor
238+join ::
239+ Matrix e a rows ->
240+ Matrix e b rows ->
241+ Matrix e (Either a b) rows
242+join (M a) (M b) = M (I.Join a b)
243+
244+infixl 3 |||
245+-- | Matrix 'Join' constructor
246+(|||) ::
247+ Matrix e a rows ->
248+ Matrix e b rows ->
249+ Matrix e (Either a b) rows
250+(|||) = join
251+
252+-- | Matrix 'Fork' constructor
253+fork ::
254+ Matrix e cols a ->
255+ Matrix e cols b ->
256+ Matrix e cols (Either a b)
257+fork (M a) (M b) = M (I.Fork a b)
258+
259+infixl 2 ===
260+-- | Matrix 'Fork' constructor
261+(===) ::
262+ Matrix e cols a ->
263+ Matrix e cols b ->
264+ Matrix e cols (Either a b)
265+(===) = fork
266+
267+-- Functor hierarchy
268+
269+-- | Functor instance equivalent function
270+fmapM ::
271+ ( Liftable e a b,
272+ CountableDimsN a b,
273+ FLN b a
274+ )
275+ =>
276+ (a -> b) -> Matrix e c a -> Matrix e c b
277+fmapM f m = fromF f . m
278+
279+-- | Applicative instance equivalent 'unit' function,
280+unitM :: (Num e) => Matrix e () ()
281+unitM = one 1
282+
283+-- | Applicative instance equivalent 'unit' function,
284+multM ::
285+ ( CountableDimsN a b,
286+ CountableN (a, b),
287+ Num e,
288+ FLN (a, b) a,
289+ FLN (a, b) b,
290+ TrivialP a b
291+ ) => Matrix e c a -> Matrix e c b -> Matrix e c (a, b)
292+multM = kr
293+
294+-- | Monad instance equivalent 'return' function,
295+returnM ::
296+ forall e a .
297+ ( Num e,
298+ Enum e,
299+ Enum a,
300+ FLN () a,
301+ Countable a
302+ ) => a -> Matrix e One a
303+returnM a = col l
304+ where
305+ i = fromInteger $ natVal (Proxy :: Proxy (I.Count a))
306+ x = fromEnum a
307+ l = take x [0,0..] ++ [1] ++ take (i - x - 1) [0,0..]
308+
309+-- | Monad instance equivalent '(>>=)' function,
310+bindM :: (Num e) => Matrix e a b -> Matrix e b c -> Matrix e a c
311+bindM = flip comp
312+
313+-- Construction
314+
315+-- | Build a matrix out of a list of list of elements. Throws a runtime
316+-- error if the dimensions do not match.
317+fromLists :: (FLN cols rows) => [[e]] -> Matrix e cols rows
318+fromLists = M . I.fromLists
319+
320+-- | Matrix builder function. Constructs a matrix provided with
321+-- a construction function that operates with indices.
322+matrixBuilder' ::
323+ (FLN cols rows, CountableDimsN cols rows )
324+ => ((Int, Int) -> e) -> Matrix e cols rows
325+matrixBuilder' = M . I.matrixBuilder'
326+
327+-- | Matrix builder function. Constructs a matrix provided with
328+-- a construction function that operates with arbitrary types.
329+matrixBuilder ::
330+ ( FLN a b,
331+ Enum a,
332+ Enum b,
333+ Bounded a,
334+ Bounded b,
335+ Eq a,
336+ Countable b
337+ ) => ((a, b) -> e) -> Matrix e a b
338+matrixBuilder f = M (I.matrixBuilder f)
339+
340+-- | Constructs a column vector matrix
341+col :: (FLN () rows) => [e] -> Matrix e One rows
342+col = M . I.col
343+
344+-- | Constructs a row vector matrix
345+row :: (FLN cols ()) => [e] -> Matrix e cols One
346+row = M . I.row
347+
348+-- | Lifts functions to matrices with arbitrary dimensions.
349+--
350+-- NOTE: Be careful to not ask for a matrix bigger than the cardinality of
351+-- types @a@ or @b@ allows.
352+fromF' ::
353+ ( Liftable e a b,
354+ CountableDimsN cols rows,
355+ FLN rows cols
356+ ) =>
357+ (a -> b) -> Matrix e cols rows
358+fromF' = M . I.fromF'
359+
360+-- | Lifts functions to matrices with dimensions matching @a@ and @b@
361+-- cardinality's.
362+fromF ::
363+ ( Liftable e a b,
364+ CountableDimsN a b,
365+ FLN b a
366+ ) =>
367+ (a -> b) -> Matrix e a b
368+fromF = M . I.fromF
369+
370+-- | Lifts relation functions to Boolean Matrix
371+toRel ::
372+ ( Liftable (Natural 0 1) a b,
373+ CountableDims a b,
374+ FLN b a
375+ ) => (a -> b -> Bool) -> Matrix (Natural 0 1) a b
376+toRel = M . I.toRel
377+
378+-- Conversion
379+
380+-- | Converts a matrix to a list of lists of elements.
381+toLists :: Matrix e cols rows -> [[e]]
382+toLists (M m) = I.toLists m
383+
384+-- | Converts a matrix to a list of elements.
385+toList :: Matrix e cols rows -> [e]
386+toList (M m) = I.toList m
387+
388+-- Zeros Matrix
389+
390+-- | The zero matrix. A matrix wholly filled with zeros.
391+zeros ::
392+ (Num e, FLN cols rows, CountableDimsN cols rows)
393+ => Matrix e cols rows
394+zeros = M I.zeros
395+
396+-- Ones Matrix
397+
398+-- | The ones matrix. A matrix wholly filled with ones.
399+--
400+-- Also known as T (Top) matrix.
401+ones ::
402+ (Num e, FLN cols rows, CountableDimsN cols rows)
403+ => Matrix e cols rows
404+ones = M I.ones
405+
406+-- Const Matrix
407+
408+-- | The constant matrix constructor. A matrix wholly filled with a given
409+-- value.
410+constant ::
411+ (Num e, FLN cols rows, CountableDimsN cols rows)
412+ => e -> Matrix e cols rows
413+constant = M . I.constant
414+
415+-- Bang Matrix
416+
417+-- | The T (Top) row vector matrix.
418+bang ::
419+ forall e cols.
420+ (Num e, Enum e, FLN cols (), CountableN cols) =>
421+ Matrix e cols One
422+bang = M I.bang
423+
424+-- | Point constant relation
425+point ::
426+ ( Bounded a,
427+ Enum a,
428+ Eq a,
429+ Num e,
430+ Ord e,
431+ CountableN a,
432+ FLN a One
433+ ) => a -> Matrix e One a
434+point = fromF . const
435+
436+-- iden Matrix
437+
438+-- | iden matrix
439+iden ::
440+ (Num e, FLN a a, CountableN a) =>
441+ Matrix e a a
442+iden = M I.iden
443+{-# NOINLINE iden #-}
444+
445+-- Matrix composition (MMM)
446+
447+-- | Matrix composition. Equivalent to matrix-matrix multiplication.
448+--
449+-- This definition takes advantage of divide-and-conquer and fusion laws
450+-- from LAoP.
451+comp :: (Num e) => Matrix e cr rows -> Matrix e cols cr -> Matrix e cols rows
452+comp (M a) (M b) = M (I.comp a b)
453+{-# NOINLINE comp #-}
454+{-# RULES
455+ "comp/iden1" forall m. comp m iden = m ;
456+ "comp/iden2" forall m. comp iden m = m
457+#-}
458+
459+-- Scalar multiplication of matrices
460+
461+infixl 7 .|
462+-- | Scalar multiplication of matrices.
463+(.|) :: Num e => e -> Matrix e cols rows -> Matrix e cols rows
464+(.|) e (M m) = M (e I..| m)
465+
466+-- Scalar division of matrices
467+
468+infixl 7 ./
469+-- | Scalar multiplication of matrices.
470+(./) :: Fractional e => Matrix e cols rows -> e -> Matrix e cols rows
471+(./) (M m) e = M (m I../ e)
472+
473+-- | Biproduct first component projection
474+p1 ::
475+ ( Num e,
476+ CountableDimsN n m,
477+ FLN n m,
478+ FLN m m
479+ ) =>
480+ Matrix e (Either m n) m
481+p1 = M I.p1
482+
483+-- | Biproduct second component projection
484+p2 ::
485+ ( Num e,
486+ CountableDimsN n m,
487+ FLN m n,
488+ FLN n n
489+ ) =>
490+ Matrix e (Either m n) n
491+p2 = M I.p2
492+
493+-- Injections
494+
495+-- | Biproduct first component injection
496+i1 ::
497+ ( Num e,
498+ CountableDimsN n m,
499+ FLN n m,
500+ FLN m m
501+ ) =>
502+ Matrix e m (Either m n)
503+i1 = tr p1
504+
505+-- | Biproduct second component injection
506+i2 ::
507+ ( Num e,
508+ CountableDimsN n m,
509+ FLN m n,
510+ FLN n n
511+ ) =>
512+ Matrix e n (Either m n)
513+i2 = tr p2
514+
515+-- Dimensions
516+
517+-- | Obtain the number of rows.
518+--
519+-- NOTE: The 'KnownNat' constraint is needed in order to obtain the
520+-- dimensions in constant time. For a version that doesn't require the
521+-- constraint see 'rows''.
522+rows :: (CountableN rows) => Matrix e cols rows -> Int
523+rows (M m) = I.rows m
524+
525+-- | Obtain the number of rows in an inefficient manner, but without any
526+-- constraints.
527+--
528+-- For a more efficient version see 'rows'.
529+rows' :: Matrix e cols rows -> Int
530+rows' (M m) = I.rows' m
531+
532+-- | Obtain the number of columns.
533+--
534+-- NOTE: The 'KnownNat' constraint is needed in order to obtain the
535+-- dimensions in constant time. For a version that doesn't require the
536+-- constraint see 'columns''.
537+columns :: (CountableN cols) => Matrix e cols rows -> Int
538+columns (M m) = I.columns m
539+
540+-- | Obtain the number of columns in an inefficient manner, but without any
541+-- constraints.
542+--
543+-- For a more efficient version see 'columns'.
544+columns' :: Matrix e cols rows -> Int
545+columns' (M m) = I.columns' m
546+
547+-- Coproduct Bifunctor
548+
549+infixl 5 -|-
550+
551+-- | Matrix coproduct functor also known as matrix direct sum.
552+(-|-) ::
553+ ( Num e,
554+ CountableDimsN j k,
555+ FLN k k,
556+ FLN j k,
557+ FLN k j,
558+ FLN j j
559+ ) =>
560+ Matrix e n k ->
561+ Matrix e m j ->
562+ Matrix e (Either n m) (Either k j)
563+(-|-) (M a) (M b) = M ((I.-|-) a b)
564+
565+-- Khatri Rao Product and projections
566+
567+-- | Khatri Rao product first component projection matrix.
568+fstM ::
569+ forall e m k .
570+ ( Num e,
571+ CountableDimsN m k,
572+ CountableN (m, k),
573+ FLN (m, k) m,
574+ TrivialP m k
575+ ) => Matrix e (m, k) m
576+fstM = M (I.fstM @e @(I.Normalize m) @(I.Normalize k))
577+
578+-- | Khatri Rao product second component projection matrix.
579+sndM ::
580+ forall e m k.
581+ ( Num e,
582+ CountableDimsN k m,
583+ CountableN (m, k),
584+ FLN (m, k) k,
585+ TrivialP m k
586+ ) => Matrix e (m, k) k
587+sndM = M (I.sndM @e @(I.Normalize m) @(I.Normalize k))
588+
589+-- | Khatri Rao Matrix product also known as matrix pairing.
590+--
591+-- NOTE: That this is not a true categorical product, see for instance:
592+--
593+-- @
594+-- | fstM . kr a b == a
595+-- kr a b ==> |
596+-- | sndM . kr a b == b
597+-- @
598+--
599+-- __Emphasis__ on the implication symbol.
600+kr ::
601+ forall e cols a b.
602+ ( Num e,
603+ CountableDimsN a b,
604+ CountableN (a, b),
605+ FLN (a, b) a,
606+ FLN (a, b) b,
607+ TrivialP a b
608+ ) => Matrix e cols a -> Matrix e cols b -> Matrix e cols (a, b)
609+kr a b =
610+ let fstM' = fstM @e @a @b
611+ sndM' = sndM @e @a @b
612+ in comp (tr fstM') a * comp (tr sndM') b
613+
614+-- Product Bifunctor (Kronecker)
615+
616+infixl 4 ><
617+
618+-- | Matrix product functor also known as Kronecker product
619+(><) ::
620+ forall e m p n q.
621+ ( Num e,
622+ CountableDimsN m n,
623+ CountableDimsN p q,
624+ CountableDimsN (m, n) (p, q),
625+ FLN (m, n) m,
626+ FLN (m, n) n,
627+ FLN (p, q) p,
628+ FLN (p, q) q,
629+ TrivialP m n,
630+ TrivialP p q
631+ ) => Matrix e m p -> Matrix e n q -> Matrix e (m, n) (p, q)
632+(><) a b =
633+ let fstM' = fstM @e @m @n
634+ sndM' = sndM @e @m @n
635+ in kr (comp a fstM') (comp b sndM')
636+
637+-- Matrix abide Join Fork
638+
639+-- | Matrix "abiding" followin the 'Join'-'Fork' abide law.
640+--
641+-- Law:
642+--
643+-- @
644+-- 'Join' ('Fork' a c) ('Fork' b d) == 'Fork' ('Join' a b) ('Join' c d)
645+-- @
646+abideJF :: Matrix e cols rows -> Matrix e cols rows
647+abideJF (M m) = M (I.abideJF m)
648+
649+-- Matrix abide Fork Join
650+
651+-- | Matrix "abiding" followin the 'Fork'-'Join' abide law.
652+--
653+-- Law:
654+--
655+-- @
656+-- 'Fork' ('Join' a b) ('Join' c d) == 'Join' ('Fork' a c) ('Fork' b d)
657+-- @
658+abideFJ :: Matrix e cols rows -> Matrix e cols rows
659+abideFJ (M m) = M (I.abideFJ m)
660+
661+-- Matrix transposition
662+
663+-- | Matrix transposition.
664+tr :: Matrix e cols rows -> Matrix e rows cols
665+tr (M m) = M (I.tr m)
666+
667+-- Selective 'select' operator
668+
669+-- | Selective functors 'select' operator equivalent inspired by the
670+-- ArrowMonad solution presented in the paper.
671+selectM ::
672+ ( Num e,
673+ FLN b b,
674+ CountableN b
675+ ) => Matrix e cols (Either a b) -> Matrix e a b -> Matrix e cols b
676+selectM (M m) (M y) = M (I.select m y)
677+
678+-- McCarthy's Conditional
679+
680+-- | McCarthy's Conditional expresses probabilistic choice.
681+cond ::
682+ ( Trivial a,
683+ Trivial2 a,
684+ Trivial3 a,
685+ CountableN a,
686+ FLN () a,
687+ FLN a (),
688+ FLN a a,
689+ Liftable e a Bool
690+ )
691+ =>
692+ (a -> Bool) -> Matrix e a b -> Matrix e a b -> Matrix e a b
693+cond p (M a) (M b) = M (I.cond p a b)
694+
695+-- Pretty print
696+
697+-- | Matrix pretty printer
698+pretty :: (CountableDimsN cols rows, Show e) => Matrix e cols rows -> String
699+pretty (M m) = I.pretty m
700+
701+-- | Matrix pretty printer
702+prettyPrint :: (CountableDimsN cols rows, Show e) => Matrix e cols rows -> IO ()
703+prettyPrint (M m) = I.prettyPrint m
704+
705+-- | Zip two matrices with a given binary function
706+zipWithM :: (e -> f -> g) -> Matrix e a b -> Matrix f a b -> Matrix g a b
707+zipWithM f (M a) (M b) = M (I.zipWithM f a b)
src/LAoP/Relation.hsnew file+165
@@ -0,0 +1,165 @@
1+-----------------------------------------------------------------------------
2+-- |
3+-- Module : LAoP.Relation
4+-- Copyright : (c) Armando Santos 2019-2020
5+-- Maintainer : armandoifsantos@gmail.com
6+-- Stability : experimental
7+--
8+-- The AoP discipline generalises functions to relations which are
9+-- Boolean matrices.
10+--
11+-- This module offers many of the combinators of the Algebra of
12+-- Programming discipline. It is still under construction and very
13+-- experimental.
14+--
15+-- This is an Internal module and it is no supposed to be imported.
16+--
17+-----------------------------------------------------------------------------
18+
19+module LAoP.Relation
20+ ( -- | This definition makes use of the fact that 'Void' is
21+ -- isomorphic to 0 and '()' to 1 and captures matrix
22+ -- dimensions as stacks of 'Either's.
23+ --
24+ -- There exists two type families that make it easier to write
25+ -- matrix dimensions: 'FromNat' and 'Count'. This approach
26+ -- leads to a very straightforward implementation
27+ -- of LAoP combinators.
28+
29+ -- * Relation data type
30+ Relation (..),
31+ Boolean,
32+
33+ -- * Constraint type synonyms
34+ Countable,
35+ CountableDims,
36+ CountableN,
37+ CountableDimsN,
38+ FLN,
39+ Liftable,
40+ Trivial,
41+ TrivialP,
42+
43+ -- * Primitives
44+ one,
45+ join,
46+ (|||),
47+ fork,
48+ (===),
49+
50+ -- * Auxiliary type families
51+ FromNat,
52+ Count,
53+ Normalize,
54+
55+ -- * Matrix construction and conversion
56+ FromLists,
57+ fromLists,
58+ fromF,
59+ fromF',
60+ toRel,
61+ toLists,
62+ toList,
63+ toBool,
64+ pt,
65+ belongs,
66+ relationBuilder,
67+ zeros,
68+ ones,
69+ bang,
70+ point,
71+
72+ -- * Relational operations
73+ conv,
74+ intersection,
75+ union,
76+ sse,
77+ implies,
78+ iff,
79+ ker,
80+ img,
81+
82+ -- * Taxonomy of binary relations
83+ injective,
84+ entire,
85+ simple,
86+ surjective,
87+ representation,
88+ function,
89+ abstraction,
90+ injection,
91+ surjection,
92+ bijection,
93+ domain,
94+ range,
95+
96+ -- * Function division
97+ divisionF,
98+
99+ -- * Relation division
100+ divR,
101+ divL,
102+ divS,
103+ shrunkBy,
104+ overriddenBy,
105+
106+ -- * Relational pairing
107+ splitR,
108+
109+ -- ** Projections
110+ fstR,
111+ sndR,
112+ -- ** Bifunctor
113+ (><),
114+ -- * Relational coproduct
115+ eitherR,
116+ -- ** Injections
117+ i1,
118+ i2,
119+ -- ** Bifunctor
120+ (-|-),
121+
122+ -- * Relational "currying"
123+ trans,
124+ untrans,
125+
126+ -- * (Endo-)Relational properties
127+ reflexive,
128+ coreflexive,
129+ transitive,
130+ symmetric,
131+ antiSymmetric,
132+ irreflexive,
133+ connected,
134+ preorder,
135+ partialOrder,
136+ linearOrder,
137+ equivalence,
138+ partialEquivalence,
139+ difunctional,
140+
141+ -- * Conditionals
142+ equalizer,
143+
144+ -- ** McCarthy's Conditional
145+ predR,
146+ guard,
147+ cond,
148+
149+ -- * Relational composition and lifting
150+ iden,
151+ comp,
152+ fromF,
153+ fromF',
154+
155+ -- ** Relational application
156+ pointAp,
157+ pointApBool,
158+
159+ -- * Matrix printing
160+ pretty,
161+ prettyPrint
162+ )
163+ where
164+
165+import LAoP.Relation.Internal
src/LAoP/Relation/Internal.hsnew file+1008
@@ -0,0 +1,1008 @@
1+{-# LANGUAGE TypeFamilies #-}
2+{-# LANGUAGE ConstraintKinds #-}
3+{-# LANGUAGE GADTs #-}
4+{-# LANGUAGE UndecidableInstances #-}
5+{-# LANGUAGE FlexibleContexts #-}
6+{-# LANGUAGE TypeApplications #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+{-# LANGUAGE StandaloneDeriving #-}
9+{-# LANGUAGE DerivingVia #-}
10+{-# LANGUAGE DataKinds #-}
11+
12+-----------------------------------------------------------------------------
13+-- |
14+-- Module : LAoP.Relation.Internal
15+-- Copyright : (c) Armando Santos 2019-2020
16+-- Maintainer : armandoifsantos@gmail.com
17+-- Stability : experimental
18+--
19+-- The AoP discipline generalises functions to relations which are
20+-- Boolean matrices.
21+--
22+-- This module offers many of the combinators of the Algebra of
23+-- Programming discipline. It is still under construction and very
24+-- experimental.
25+--
26+-- This is an Internal module and it is no supposed to be imported.
27+--
28+-----------------------------------------------------------------------------
29+
30+module LAoP.Relation.Internal
31+ ( -- | This definition makes use of the fact that 'Void' is
32+ -- isomorphic to 0 and 'One' to 1 and captures matrix
33+ -- dimensions as stacks of 'Either's.
34+ --
35+ -- There exists two type families that make it easier to write
36+ -- matrix dimensions: 'FromNat' and 'Count'. This approach
37+ -- leads to a very straightforward implementation
38+ -- of LAoP combinators.
39+
40+ -- * Relation data type
41+ Relation (..),
42+ Boolean,
43+
44+ -- * Constraint type synonyms
45+ Countable,
46+ CountableDims,
47+ CountableN,
48+ CountableDimsN,
49+ FLN,
50+ Liftable,
51+ Trivial,
52+ TrivialP,
53+
54+ -- * Primitives
55+ one,
56+ join,
57+ (|||),
58+ fork,
59+ (===),
60+
61+ -- * Auxiliary type families
62+ I.FromNat,
63+ I.Count,
64+ I.Normalize,
65+
66+ -- * Matrix construction and conversion
67+ I.FromLists,
68+ fromLists,
69+ fromF',
70+ fromF,
71+ toRel,
72+ toLists,
73+ toList,
74+ toBool,
75+ pt,
76+ belongs,
77+ relationBuilder',
78+ relationBuilder,
79+ zeros,
80+ ones,
81+ bang,
82+ point,
83+
84+ -- * Relational operations
85+ conv,
86+ intersection,
87+ union,
88+ sse,
89+ implies,
90+ iff,
91+ ker,
92+ img,
93+
94+ -- * Taxonomy of binary relations
95+ injective,
96+ entire,
97+ simple,
98+ surjective,
99+ representation,
100+ function,
101+ abstraction,
102+ injection,
103+ surjection,
104+ bijection,
105+ domain,
106+ range,
107+
108+ -- * Function division
109+ divisionF,
110+
111+ -- * Relation division
112+ divR,
113+ divL,
114+ divS,
115+ shrunkBy,
116+ overriddenBy,
117+
118+ -- * Relational pairing
119+ splitR,
120+
121+ -- ** Projections
122+ fstR,
123+ sndR,
124+ -- ** Bifunctor
125+ (><),
126+ -- * Relational coproduct
127+ eitherR,
128+ -- ** Injections
129+ i1,
130+ i2,
131+ -- ** Bifunctor
132+ (-|-),
133+
134+ -- * Relational "currying"
135+ trans,
136+ untrans,
137+
138+ -- * (Endo-)Relational properties
139+ reflexive,
140+ coreflexive,
141+ transitive,
142+ symmetric,
143+ antiSymmetric,
144+ irreflexive,
145+ connected,
146+ preorder,
147+ partialOrder,
148+ linearOrder,
149+ equivalence,
150+ partialEquivalence,
151+ difunctional,
152+
153+ -- * Conditionals
154+ equalizer,
155+
156+ -- ** McCarthy's Conditional
157+ predR,
158+ guard,
159+ cond,
160+
161+ -- * Relational composition and lifting
162+ iden,
163+ comp,
164+ fromF',
165+ fromF,
166+
167+ -- ** Relational application
168+ pointAp,
169+ pointApBool,
170+
171+ -- * Matrix printing
172+ pretty,
173+ prettyPrint
174+ )
175+ where
176+
177+import Data.Void
178+import qualified LAoP.Matrix.Internal as I
179+import LAoP.Utils.Internal
180+import Control.DeepSeq
181+import Data.Bool
182+import GHC.TypeLits
183+import Prelude hiding (id, (.))
184+
185+-- | Boolean type synonym for working with boolean matrices
186+type Boolean = Natural 0 1
187+type Powerset a = List (List a)
188+
189+-- | Relation data type.
190+newtype Relation a b = R (I.Matrix Boolean (I.Normalize a) (I.Normalize b))
191+ deriving (Show, Eq, Ord, NFData) via (I.Matrix (Natural 1 1) (I.Normalize a) (I.Normalize b))
192+
193+deriving instance (Read (I.Matrix Boolean (I.Normalize a) (I.Normalize b))) => Read (Relation a b)
194+
195+-- | Constraint type synonyms to keep the type signatures less convoluted
196+type Countable a = KnownNat (I.Count a)
197+type CountableDims a b = (Countable a, Countable b)
198+type CountableN a = KnownNat (I.Count (I.Normalize a))
199+type CountableDimsN a b = (CountableN a, CountableN b)
200+type FLN a b = I.FromLists (I.Normalize a) (I.Normalize b)
201+type Liftable a b = (Bounded a, Bounded b, Enum a, Enum b, Eq b, Num Boolean, Ord Boolean)
202+type Trivial a = I.Normalize a ~ I.Normalize (I.Normalize a)
203+type TrivialP a b = I.Normalize (a, b) ~ I.Normalize (I.Normalize a, I.Normalize b)
204+
205+-- | It is possible to implement a constrained version of the category type
206+-- class.
207+instance Category Relation where
208+ type Object Relation a = (FLN a a, CountableN a)
209+ id = iden
210+ (.) = comp
211+
212+instance Num (Relation a b) where
213+ -- | Matrix addition becomes Boolean matrix disjointion
214+ (R a) + (R b) = R (I.orM a b)
215+
216+ -- | Matrix subtraction becomes Relational subtraction
217+ (R a) - (R b) = R (I.subM a b)
218+
219+ -- | Matrix multiplication becomes Boolean matrix conjointion
220+ (R a) * (R b) = R (I.andM a b)
221+
222+ -- | Matrix negation becomes Boolean matrix negation
223+ negate (R a) = R (I.negateM a)
224+
225+-- Type alias
226+type Zero = Void
227+type One = ()
228+
229+-- Primitives
230+
231+-- | Unit matrix constructor
232+one :: Boolean -> Relation One One
233+one = R . I.One
234+
235+-- | Boolean Matrix 'Join' constructor, also known as relational coproduct.
236+--
237+-- See 'eitherR'.
238+join :: Relation a c -> Relation b c -> Relation (Either a b) c
239+join (R a) (R b) = R (I.Join a b)
240+
241+infixl 3 |||
242+-- | Boolean Matrix 'Join' constructor
243+--
244+-- See 'eitherR'.
245+(|||) ::
246+ Relation a c ->
247+ Relation b c ->
248+ Relation (Either a b) c
249+(|||) = join
250+
251+-- | Boolean Matrix 'Fork' constructor, also known as relational product.
252+fork :: Relation c a -> Relation c b -> Relation c (Either a b)
253+fork (R a) (R b) = R (I.Fork a b)
254+
255+infixl 2 ===
256+-- | Boolean Matrix 'Fork' constructor
257+(===) ::
258+ Relation c a ->
259+ Relation c b ->
260+ Relation c (Either a b)
261+(===) = fork
262+
263+-- Construction
264+
265+-- | Build a matrix out of a list of list of elements. Throws a runtime
266+-- error if the dimensions do not match.
267+fromLists :: (FLN a b) => [[Boolean]] -> Relation a b
268+fromLists = R . I.fromLists
269+
270+-- | Relation builder function. Constructs a relation provided with
271+-- a construction function that operates with indices.
272+relationBuilder' ::
273+ (FLN a b, CountableDimsN a b) =>
274+ ((Int, Int) -> Boolean) -> Relation a b
275+relationBuilder' = R . I.matrixBuilder'
276+
277+-- | Relation builder function. Constructs a relation provided with
278+-- a construction function that operates with arbitrary types.
279+relationBuilder ::
280+ ( FLN a b,
281+ Enum a,
282+ Enum b,
283+ Bounded a,
284+ Bounded b,
285+ Eq a,
286+ CountableDims a b
287+ ) => ((a, b) -> Boolean) -> Relation a b
288+relationBuilder = R . I.matrixBuilder
289+
290+-- | Lifts functions to matrices with arbitrary dimensions.
291+--
292+-- NOTE: Be careful to not ask for a matrix bigger than the cardinality of
293+-- types @a@ or @b@ allows.
294+fromF' ::
295+ ( Liftable a b,
296+ CountableDimsN c d,
297+ FLN d c
298+ )
299+ => (a -> b) -> Relation c d
300+fromF' f = R (I.fromFRel' f)
301+
302+-- | Lifts functions to matrices with dimensions matching @a@ and @b@
303+-- cardinality's.
304+fromF ::
305+ ( Liftable a b,
306+ CountableDimsN a b,
307+ FLN b a
308+ )
309+ => (a -> b) -> Relation a b
310+fromF f = R (I.fromFRel f)
311+
312+-- | Lifts relation functions to 'Relation'
313+toRel ::
314+ ( Liftable a b,
315+ CountableDims a b,
316+ FLN b a
317+ )
318+ => (a -> b -> Bool) -> Relation a b
319+toRel = R . I.toRel
320+
321+-- | Lowers a 'Relation' to a function
322+fromRel ::
323+ ( Liftable a b,
324+ Eq a,
325+ CountableDimsN a b,
326+ FLN a One,
327+ FLN b One
328+ )
329+ => Relation a b -> (a -> b -> Bool)
330+fromRel r a b = pointApBool a b r
331+
332+-- Conversion
333+
334+-- | Converts a matrix to a list of lists of elements.
335+toLists :: Relation a b -> [[Boolean]]
336+toLists (R m) = I.toLists m
337+
338+-- | Converts a matrix to a list of elements.
339+toList :: Relation a b -> [Boolean]
340+toList (R m) = I.toList m
341+
342+-- | Converts a well typed 'Relation' to 'Bool'.
343+toBool :: Relation One One -> Bool
344+toBool r = case toList r of
345+ [Nat 0] -> False
346+ _ -> True
347+
348+-- | Power transpose.
349+--
350+-- Maps a relation to a set valued function.
351+pt ::
352+ ( Liftable a b,
353+ Eq a,
354+ CountableDimsN a b,
355+ FLN a One,
356+ FLN b One
357+ )
358+ => Relation a b -> (a -> List b)
359+pt r a =
360+ let (L lb) = maxBound
361+ in L [ b | b <- lb, toBool (pointAp a b r) ]
362+
363+-- | Belongs relation
364+belongs ::
365+ ( Bounded a,
366+ Enum a,
367+ Eq a,
368+ CountableDims (List a) a,
369+ FLN a (List a)
370+ )
371+ => Relation (List a) a
372+belongs = toRel elemR
373+ where
374+ elemR (L l) x = x `elem` l
375+
376+-- Zeros Matrix
377+
378+-- | The zero relation. A relation where no element of type @a@ relates
379+-- with elements of type @b@.
380+--
381+-- Also known as ⊥ (Bottom) Relation.
382+--
383+-- @
384+-- r `.` ⊥ == ⊥ `.` r == ⊥
385+-- ⊥ ``sse`` R && R ``sse`` T == True
386+-- @
387+zeros ::
388+ (FLN a b, CountableDimsN a b) =>
389+ Relation a b
390+zeros = relationBuilder' (const (nat 0))
391+
392+-- Ones Matrix
393+
394+-- | The ones relation. A relation where every element of type @a@ relates
395+-- with every element of type @b@.
396+--
397+-- Also known as T (Top) Relation or universal Relation.
398+--
399+-- @
400+-- ⊥ ``sse`` R && R ``sse`` T == True
401+-- @
402+ones ::
403+ (FLN a b, CountableDimsN a b) =>
404+ Relation a b
405+ones = relationBuilder' (const (nat 1))
406+
407+-- Bang Matrix
408+
409+-- | The T (Top) row vector relation.
410+bang ::
411+ (FLN a One, CountableN a) =>
412+ Relation a One
413+bang = ones
414+
415+-- | Point constant relation
416+point ::
417+ ( Bounded a,
418+ Enum a,
419+ Eq a,
420+ CountableN a,
421+ FLN a One
422+ ) => a -> Relation One a
423+point = fromF . const
424+
425+-- iden Matrix
426+
427+-- | iden matrix
428+--
429+-- @
430+-- 'iden' `.` r == r == r `.` 'iden'
431+-- @
432+iden ::
433+ (FLN a a, CountableN a) => Relation a a
434+iden = relationBuilder' (bool (nat 0) (nat 1) . uncurry (==))
435+
436+-- | Relational composition
437+--
438+-- @
439+-- r `.` (s `.` p) = (r `.` s) `.` p
440+-- @
441+comp :: Relation b c -> Relation a b -> Relation a c
442+comp (R a) (R b) = R (I.compRel a b)
443+
444+-- | Relational right division
445+--
446+-- @'divR' x y@ is the largest relation @z@ which,
447+-- pre-composed with @y@, approximates @x@.
448+divR :: Relation b c -> Relation b a -> Relation a c
449+divR (R x) (R y) = R (I.divR x y)
450+
451+-- | Relational left division
452+--
453+-- The dual division operator:
454+--
455+-- @
456+-- 'divL' y x == 'conv' ('divR' ('conv' x) ('conv' y)
457+-- @
458+divL :: Relation c b -> Relation a b -> Relation a c
459+divL (R x) (R y) = R (I.divL x y)
460+
461+-- | Relational symmetric division
462+--
463+-- @'pointAp' c b ('divS' s r)@ means that @b@ and @c@
464+-- are related to exactly the same outputs by @r@ and by @s@.
465+divS :: Relation c a -> Relation b a -> Relation c b
466+divS (R x) (R y) = R (I.divS x y)
467+
468+-- | Relational shrinking.
469+--
470+-- @r ``shrunkBy`` s@ is the largest part of @r@ such that,
471+-- if it yields an output for an input @x@, it must be a maximum,
472+-- with respect to @s@, among all possible outputs of @x@ by @r@.
473+shrunkBy :: Relation b a -> Relation a a -> Relation b a
474+shrunkBy r s = r `intersection` divR s (conv r)
475+
476+-- | Relational overriding.
477+--
478+-- @r ``overriddenBy`` s@ yields the relation which contains the
479+-- whole of @s@ and that part of @r@ where @s@ is undefined.
480+--
481+-- @
482+-- 'zeros' ``overriddenBy`` s == s
483+-- r ``overriddenBy`` 'zeros' == r
484+-- r ``overriddenBy`` r == r
485+-- @
486+overriddenBy ::
487+ ( FLN b b,
488+ CountableN b
489+ ) => Relation a b -> Relation a b -> Relation a b
490+overriddenBy r s = s `union` r `intersection` divR zeros (conv s)
491+
492+-- | Relational application.
493+--
494+-- If @a@ and @b@ are related by 'Relation' @r@
495+-- then @'pointAp' a b r == 'one' ('nat' 1)@
496+pointAp ::
497+ ( Liftable a b,
498+ Eq a,
499+ CountableDimsN a b,
500+ FLN a One,
501+ FLN b One
502+ ) => a -> b -> Relation a b -> Relation One One
503+pointAp a b r = conv (point b) . r . point a
504+
505+-- | Relational application
506+--
507+-- The same as 'pointAp' but converts 'Boolean' to 'Bool'
508+pointApBool ::
509+ ( Liftable a b,
510+ Eq a,
511+ CountableDimsN a b,
512+ FLN a One,
513+ FLN b One
514+ ) => a -> b -> Relation a b -> Bool
515+pointApBool a b r = toBool $ conv (point b) . r . point a
516+
517+-- | Relational converse
518+--
519+-- Given binary 'Relation' r, writing @'pointAp' a b r@
520+-- (read: “@b@ is related to @a@ by @r@”) means the same as
521+-- @'pointAp' b a ('conv' r)@, where @'conv' r@ is said to be
522+-- the converse of @r@.
523+-- In terms of grammar, @'conv' r@ corresponds to the passive voice
524+conv :: Relation a b -> Relation b a
525+conv (R a) = R (I.tr a)
526+
527+-- | Relational inclusion (subset or equal)
528+sse :: Relation a b -> Relation a b -> Bool
529+sse a b = a <= b
530+
531+-- | Relational implication (the same as @'sse'@)
532+implies :: Relation a b -> Relation a b -> Relation a b
533+implies r s = negate r `union` s
534+
535+-- | Relational bi-implication
536+iff :: Relation a b -> Relation a b -> Bool
537+iff r s = r == s
538+
539+-- | Relational intersection
540+--
541+-- Lifts pointwise conjointion.
542+--
543+-- @
544+-- (r ``intersection`` s) ``intersection`` t == r ``intersection`` (s ``intersection`` t)
545+-- x ``sse`` r ``intersection`` s == x ``intersection`` r && x ``intersection`` s
546+-- @
547+intersection :: Relation a b -> Relation a b -> Relation a b
548+intersection a b = a * b
549+
550+-- | Relational union
551+--
552+-- Lifts pointwise disjointion.
553+--
554+-- @
555+-- (r ``union`` s) ``union`` t == r `'union' (s ``union`` t)
556+-- r ``union`` s ``sse`` x == r ``sse`` x && s ``sse`` x
557+-- r `.` (s ``union`` t) == (r `.` s) ``union`` (r `.` t)
558+-- (s ``union`` t) `.` r == (s `.` r) ``union`` (t `.` r)
559+-- @
560+union :: Relation a b -> Relation a b -> Relation a b
561+union a b = a + b
562+
563+-- | Relation Kernel
564+--
565+-- @
566+-- 'ker' r == 'conv' r `.` r
567+-- 'ker' r == 'img' ('conv' r)
568+-- @
569+ker :: Relation a b -> Relation a a
570+ker r = conv r . r
571+
572+-- | Relation Image
573+--
574+-- @
575+-- 'img' r == r `.` conv r
576+-- 'img' r == 'ker' ('conv' r)
577+-- @
578+img :: Relation a b -> Relation b b
579+img r = r . conv r
580+
581+-- | Function division. Special case of 'divS'.
582+--
583+-- NOTE: _This is only valid_ if @f@ and @g@ are 'function's, i.e. 'simple' and
584+-- 'entire'.
585+--
586+-- @'divisionF' f g == 'conv' g `.` f@
587+divisionF :: Relation a c -> Relation b c -> Relation a b
588+divisionF f g = conv g . f
589+
590+-- Taxonomy of binary relations
591+
592+-- | A 'Relation' @r@ is 'simple' 'iff' @'coreflexive' ('img' r)@
593+simple :: (CountableN b, FLN b b) => Relation a b -> Bool
594+simple = coreflexive . img
595+
596+-- | A 'Relation' @r@ is 'injective' 'iff' @'coreflexive' ('ker' r)@
597+injective :: (CountableN a, FLN a a) => Relation a b -> Bool
598+injective = coreflexive . ker
599+
600+-- | A 'Relation' @r@ is 'entire' 'iff' @'reflexive' ('ker' r)@
601+entire :: (CountableN a, FLN a a) => Relation a b -> Bool
602+entire = reflexive . ker
603+
604+-- | A 'Relation' @r@ is 'surjective' 'iff' @'reflexive' ('img' r)@
605+surjective :: (CountableN b, FLN b b) => Relation a b -> Bool
606+surjective = reflexive . img
607+
608+-- | A 'Relation' @r@ is a 'function' 'iff' @'simple' r && 'entire' r@
609+--
610+-- A 'function' @f@ enjoys the following properties, where @r@ and @s@ are binary
611+-- relations:
612+--
613+-- @
614+-- f `.` r ``sse`` s == r ``sse`` f `.` s
615+-- r `.` f ``sse`` s == r ``sse`` s `.` f
616+-- @
617+function ::
618+ ( CountableDimsN a b,
619+ FLN a a,
620+ FLN b b
621+ )
622+ => Relation a b -> Bool
623+function r = simple r && entire r
624+
625+-- | A 'Relation' @r@ is a 'representation' 'iff' @'injective' r && 'entire' r@
626+representation ::
627+ ( CountableN a,
628+ FLN a a
629+ )
630+ => Relation a b -> Bool
631+representation r = injective r && entire r
632+
633+-- | A 'Relation' @r@ is an 'abstraction' 'iff' @'surjective' r && 'simple' r@
634+abstraction ::
635+ ( CountableN b,
636+ FLN b b
637+ )
638+ => Relation a b -> Bool
639+abstraction r = surjective r && simple r
640+
641+-- | A 'Relation' @r@ is a 'surjection' 'iff' @'function' r && 'abstraction' r@
642+surjection ::
643+ ( CountableDimsN a b,
644+ FLN a a,
645+ FLN b b
646+ )
647+ => Relation a b -> Bool
648+surjection r = function r && abstraction r
649+
650+-- | A 'Relation' @r@ is a 'injection' 'iff' @'function' r && 'representation' r@
651+injection ::
652+ ( CountableDimsN a b,
653+ FLN a a,
654+ FLN b b
655+ )
656+ => Relation a b -> Bool
657+injection r = function r && representation r
658+
659+-- | A 'Relation' @r@ is an 'bijection' 'iff' @'injection' r && 'surjection' r@
660+bijection ::
661+ ( CountableDimsN a b,
662+ FLN b b,
663+ FLN a a
664+ ) => Relation a b -> Bool
665+bijection r = injection r && surjection r
666+
667+-- Properties of relations
668+
669+-- | A 'Relation' @r@ is 'reflexive' 'iff' @'id' ``sse`` r@
670+reflexive :: (CountableN a, FLN a a) => Relation a a -> Bool
671+reflexive r = id <= r
672+
673+-- | A 'Relation' @r@ is 'coreflexive' 'iff' @r ``sse`` 'id'@
674+coreflexive :: (CountableN a, FLN a a) => Relation a a -> Bool
675+coreflexive r = r <= id
676+
677+-- | A 'Relation' @r@ is 'transitive' 'iff' @(r `.` r) ``sse`` r@
678+transitive :: Relation a a -> Bool
679+transitive r = (r . r) `sse` r
680+
681+-- | A 'Relation' @r@ is 'symmetric' 'iff' @r == 'conv' r@
682+symmetric :: Relation a a -> Bool
683+symmetric r = r == conv r
684+
685+-- | A 'Relation' @r@ is anti-symmetric 'iff' @(r ``intersection`` 'conv' r) ``sse`` 'id'@
686+antiSymmetric :: (CountableN a, FLN a a) => Relation a a -> Bool
687+antiSymmetric r = (r `intersection` conv r) `sse` id
688+
689+-- | A 'Relation' @r@ is 'irreflexive' 'iff' @(r ``intersection`` 'id') == 'zeros'@
690+irreflexive :: (CountableN a, FLN a a) => Relation a a -> Bool
691+irreflexive r = (r `intersection` id) == zeros
692+
693+-- | A 'Relation' @r@ is 'connected' 'iff' @(r ``union`` 'conv' r) == 'ones'@
694+connected :: (CountableN a, FLN a a) => Relation a a -> Bool
695+connected r = (r `union` conv r) == ones
696+
697+-- | A 'Relation' @r@ is a 'preorder' 'iff' @'reflexive' r && 'transitive' r@
698+preorder :: (CountableN a, FLN a a) => Relation a a -> Bool
699+preorder r = reflexive r && transitive r
700+
701+-- | A 'Relation' @r@ is a partial-order 'iff' @'antiSymmetric' r && 'preorder' r@
702+partialOrder :: (CountableN a, FLN a a) => Relation a a -> Bool
703+partialOrder r = antiSymmetric r && preorder r
704+
705+-- | A 'Relation' @r@ is a linear-order 'iff' @'connected' r && 'partialOrder' r@
706+linearOrder :: (CountableN a, FLN a a) => Relation a a -> Bool
707+linearOrder r = connected r && partialOrder r
708+
709+-- | A 'Relation' @r@ is an 'equivalence' 'iff' @'symmetric' r && 'preorder' r@
710+equivalence :: (CountableN a, FLN a a) => Relation a a -> Bool
711+equivalence r = symmetric r && preorder r
712+
713+-- | A 'Relation' @r@ is a partial-equivalence 'iff' @'partialOrder' r && 'equivalence' r@
714+partialEquivalence :: (CountableN a, FLN a a) => Relation a a -> Bool
715+partialEquivalence r = partialOrder r && equivalence r
716+
717+-- | A 'Relation' @r@ is 'difunctional' or regular wherever
718+-- @r `.` 'conv' r `.` r == r@
719+difunctional :: Relation a b -> Bool
720+difunctional r = r . conv r . r == r
721+
722+-- Relational pairing
723+
724+-- | Relational pairing.
725+--
726+-- NOTE: That this is not a true categorical product, see for instance:
727+--
728+-- @
729+-- | 'fstR' `.` 'splitR' a b ``sse`` a
730+-- 'splitR' a b <=> |
731+-- | 'sndR' `.` 'splitR' a b ``sse`` b
732+-- @
733+--
734+-- __Emphasis__ on the 'sse'.
735+--
736+-- @
737+-- 'splitR' r s `.` f == 'splitR' (r `.` f) (s `.` f)
738+-- (R '><' S) `.` 'splitR' p q == 'splitR' (r `.` p) (s `.` q)
739+-- 'conv' ('splitR' r s) `.` 'splitR' x y == ('conv' r `.` x) ``intersection`` ('conv' s `.` y)
740+-- @
741+--
742+-- @
743+-- 'eitherR' ('splitR' r s) ('splitR' t v) == 'splitR' ('eitherR' r t) ('eitherR' s v)
744+-- @
745+splitR ::
746+ ( CountableDimsN a b,
747+ CountableN (a, b),
748+ FLN (a, b) a,
749+ FLN (a, b) b,
750+ TrivialP a b
751+ )
752+ => Relation c a -> Relation c b -> Relation c (a, b)
753+splitR (R f) (R g) = R (I.kr f g)
754+
755+-- | Relational pairing first component projection
756+--
757+-- @
758+-- 'fstR' `.` 'splitR' r s ``sse`` r
759+-- @
760+fstR ::
761+ forall a b .
762+ ( CountableDimsN a b,
763+ CountableN (a, b),
764+ FLN (a, b) a,
765+ TrivialP a b
766+ )
767+ => Relation (a, b) a
768+fstR = R (I.fstM @Boolean @(I.Normalize a) @(I.Normalize b))
769+
770+-- | Relational pairing second component projection
771+--
772+-- @
773+-- 'sndR' `.` 'splitR' r s ``sse`` s
774+-- @
775+sndR ::
776+ forall a b .
777+ ( CountableDimsN a b,
778+ CountableN (a, b),
779+ FLN (a, b) b,
780+ TrivialP a b
781+ )
782+ => Relation (a, b) b
783+sndR = R (I.sndM @Boolean @(I.Normalize a) @(I.Normalize b))
784+
785+-- Relational pairing functor
786+
787+infixl 4 ><
788+-- | Relational pairing functor
789+--
790+-- @
791+-- r '><' s == 'splitR' (r `.` fstR) (s `.` sndR)
792+-- (r '><' s) `.` (p '><' q) == (r `.` p) '><' (s `.` q)
793+-- @
794+(><) ::
795+ ( CountableDimsN a b,
796+ CountableDimsN c d,
797+ CountableDimsN (a, c) (b, d),
798+ FLN (a, c) a,
799+ FLN (a, c) c,
800+ FLN (b, d) b,
801+ FLN (b, d) d,
802+ TrivialP a c,
803+ TrivialP b d
804+ )
805+ => Relation a b -> Relation c d -> Relation (a, c) (b, d)
806+(><) (R a) (R b) = R ((I.><) a b)
807+
808+-- Relational co-products
809+
810+-- | Relational coproduct.
811+--
812+-- @
813+-- | 'eitherR' a b `.` 'i1' == a
814+-- 'eitherR' a b <=> |
815+-- | 'eitherR' a b `.` 'i2' == b
816+-- @
817+--
818+-- @
819+-- 'eitherR' r s `.` 'conv' ('eitherR' t u) == (r `.` 'conv' t) ``union`` (s `.` 'conv' u)
820+-- @
821+--
822+-- @
823+-- 'eitherR' ('splitR' r s) ('splitR' t v) == 'splitR' ('eitherR' r t) ('eitherR' s v)
824+-- @
825+eitherR :: Relation a c -> Relation b c -> Relation (Either a b) c
826+eitherR = join
827+
828+-- | Relational coproduct first component injection
829+--
830+-- @
831+-- 'img' 'i1' ``union`` 'img' 'i2' == 'id'
832+-- 'i1' `.` 'i2' = 'zeros'
833+-- @
834+i1 ::
835+ ( CountableDimsN a b,
836+ FLN b a,
837+ FLN a a
838+ )
839+ => Relation a (Either a b)
840+i1 = R I.i1
841+
842+-- | Relational coproduct second component injection
843+--
844+-- @
845+-- 'img' 'i1' ``union`` 'img' 'i2' == 'id'
846+-- 'i1' `.` 'i2' = 'zeros'
847+-- @
848+i2 ::
849+ ( CountableDimsN a b,
850+ FLN a b,
851+ FLN b b
852+ )
853+ => Relation b (Either a b)
854+i2 = R I.i2
855+
856+infixl 5 -|-
857+
858+-- | Relational coproduct functor.
859+--
860+-- @
861+-- r '-|-' s == 'eitherR' ('i1' `.` r) ('i2' `.` s)
862+-- @
863+(-|-) ::
864+ ( CountableDimsN b d,
865+ FLN b b,
866+ FLN d b,
867+ FLN b d,
868+ FLN d d
869+ )
870+ => Relation a b -> Relation c d -> Relation (Either a c) (Either b d)
871+(-|-) (R a) (R b) = R ((I.-|-) a b)
872+
873+-- Relational "Currying"
874+
875+-- | Relational 'trans'
876+--
877+-- Every n-ary relation can be expressed as a binary relation through
878+-- 'trans'/'untrans';
879+-- more-over, where each particular attribute is placed (input/output) is irrelevant.
880+trans ::
881+ ( CountableDimsN a b,
882+ CountableN c,
883+ CountableDimsN (a, b) (c, b),
884+ FLN (c, b) c,
885+ FLN (c, b) b,
886+ FLN (a, b) a,
887+ FLN (a, b) b,
888+ Trivial (a, b),
889+ Trivial (c, b),
890+ TrivialP a b,
891+ TrivialP c b
892+ )
893+ => Relation (a, b) c -> Relation a (c, b)
894+trans r = splitR r sndR . conv fstR
895+
896+-- | Relational 'untrans'
897+--
898+-- Every n-ary relation can be expressed as a binary relation through
899+-- 'trans'/'untrans';
900+-- more-over, where each particular attribute is placed (input/output) is irrelevant.
901+untrans ::
902+ ( CountableDimsN a b,
903+ CountableN c,
904+ CountableDimsN (a, b) (c, b),
905+ FLN (c, b) c,
906+ FLN (c, b) b,
907+ FLN (a, b) b,
908+ FLN (a, b) a,
909+ Trivial (a, b),
910+ Trivial (c, b),
911+ TrivialP a b,
912+ TrivialP c b
913+ )
914+ => Relation a (c, b) -> Relation (a, b) c
915+untrans s = fstR . conv (splitR (conv s) sndR)
916+
917+-- | Transforms predicate @p@ into a correflexive relation.
918+--
919+-- @
920+-- 'predR' ('const' True) == 'id'
921+-- 'predR' ('const' False) == 'zeros'
922+-- @
923+--
924+-- @
925+-- 'predR' q `.` 'predR' p == 'predR' q ``union`` 'predR' p
926+-- @
927+predR ::
928+ ( Bounded a,
929+ Enum a,
930+ Countable a,
931+ CountableN a,
932+ FLN a a,
933+ FLN Bool a
934+ )
935+ => Relation a Bool -> Relation a a
936+predR p = id `intersection` divisionF (fromF (const True)) p
937+
938+-- | Equalizes functions @f@ and @g@.
939+-- That is, @'equalizer' f g@ is the largest coreflexive
940+-- that restricts @g@ so that @f@ and @g@ yield the same outputs.
941+--
942+-- @
943+-- 'equalizer' r r == 'id'
944+-- 'equalizer' ('point' True) ('point' False) == 'zeros'
945+-- @
946+equalizer ::
947+ ( CountableN a,
948+ FLN a a
949+ )
950+ => Relation a b -> Relation a b -> Relation a a
951+equalizer f g = id `intersection` divisionF f g
952+
953+-- | Relational conditional guard.
954+--
955+-- @
956+-- 'guard' p = 'i2' ``overriddenBy`` 'i1' `.` 'predR' p
957+-- @
958+guard ::
959+ ( Bounded b,
960+ Enum b,
961+ CountableN b,
962+ Countable b,
963+ FLN b b,
964+ FLN Bool b
965+ ) => Relation b Bool -> Relation b (Either b b)
966+guard p = conv (eitherR (predR p) (predR (negate p)))
967+
968+-- | Relational McCarthy's conditional.
969+cond ::
970+ ( Bounded b,
971+ Enum b,
972+ Countable b,
973+ CountableN b,
974+ FLN b b,
975+ FLN Bool b
976+ )
977+ => Relation b Bool -> Relation b c -> Relation b c -> Relation b c
978+cond p r s = eitherR r s . guard p
979+
980+-- | Relational domain.
981+--
982+-- For injective relations, 'domain' and 'ker'nel coincide,
983+-- since @'ker' r ``sse`` 'id'@ in such situations.
984+domain ::
985+ ( CountableN a,
986+ FLN a a
987+ ) => Relation a b -> Relation a a
988+domain r = ker r `intersection` id
989+
990+-- | Relational range.
991+--
992+-- For functions, 'range' and 'img' (image) coincide,
993+-- since @'img' f ``sse`` id@ for any @f@.
994+range ::
995+ ( CountableN b,
996+ FLN b b
997+ ) => Relation a b -> Relation b b
998+range r = img r `intersection` id
999+
1000+-- Relation pretty print
1001+
1002+-- | Relation pretty printing
1003+pretty :: (CountableDimsN a b) => Relation a b -> String
1004+pretty (R a) = I.pretty a
1005+
1006+-- | Relation pretty printing
1007+prettyPrint :: (CountableDimsN a b) => Relation a b -> IO ()
1008+prettyPrint (R a) = I.prettyPrint a
src/Utils.hs → src/LAoP/Utils.hsrenamed+10−3
@@ -1,6 +1,6 @@
11-----------------------------------------------------------------------------
22-- |
3−-- Module : Utils
3+-- Module : LAoP.Utils
44-- Copyright : (c) Armando Santos 2019-2020
55-- Maintainer : armandoifsantos@gmail.com
66-- Stability : experimental
@@ -15,7 +15,7 @@
1515--
1616-----------------------------------------------------------------------------
1717
18−module Utils
18+module LAoP.Utils
1919 ( -- | Utility module that provides the 'Natural' data type.
2020 -- The semantic associated with this data type is that
2121 -- it's meant to be a restricted 'Int' value. For example
@@ -93,7 +93,14 @@ module Utils
9393 -- 'Natural' typed functions.
9494 coerceNat,
9595 coerceNat2,
96+ coerceNat3,
97+
98+ -- * List data type
99+ List (..),
100+
101+ -- * Category type-class
102+ Category(..)
96103 )
97104where
98105
99−import Utils.Internal
106+import LAoP.Utils.Internal
src/LAoP/Utils/Internal.hsnew file+196
@@ -0,0 +1,196 @@
1+{-# LANGUAGE TypeFamilies #-}
2+{-# LANGUAGE DeriveGeneric #-}
3+{-# LANGUAGE TypeApplications #-}
4+{-# LANGUAGE DataKinds #-}
5+{-# LANGUAGE FlexibleInstances #-}
6+{-# LANGUAGE GeneralizedNewtypeDeriving #-}
7+{-# LANGUAGE ScopedTypeVariables #-}
8+
9+module LAoP.Utils.Internal
10+ (
11+ -- * 'Natural' data type
12+ Natural(..),
13+ nat,
14+
15+ -- * Coerce auxiliar functions to help promote 'Int' typed functions to
16+ -- 'Natural' typed functions.
17+ coerceNat,
18+ coerceNat2,
19+ coerceNat3,
20+
21+ -- * 'List' data type
22+ List (..),
23+
24+ -- * Category type class
25+ Category(..)
26+ )
27+where
28+
29+import Data.Coerce
30+import Data.Proxy
31+import Data.List
32+import Data.Maybe
33+import GHC.TypeLits
34+import Control.DeepSeq
35+import GHC.Generics
36+import Data.Kind
37+import Prelude hiding (id, (.))
38+import qualified Prelude
39+
40+-- | Wrapper around 'Int's that have a restrictive semantic associated.
41+-- A value of type @'Natural' n m@ can only be instanciated with some 'Int'
42+-- @i@ that's @n <= i <= m@.
43+newtype Natural (start :: Nat) (end :: Nat) = Nat Int
44+ deriving (Show, Read, Eq, Ord, NFData, Generic)
45+
46+-- | Throws a runtime error if any of the operations overflows or
47+-- underflows.
48+instance (KnownNat n, KnownNat m) => Num (Natural n m) where
49+ (Nat a) + (Nat b) = nat @n @m (a + b)
50+ (Nat a) - (Nat b) = nat @n @m (a - b)
51+ (Nat a) * (Nat b) = nat @n @m (a * b)
52+ abs (Nat a) = nat @n @m (abs a)
53+ signum (Nat a) = nat @n @m (signum a)
54+ fromInteger i = nat @n @m (fromInteger i)
55+
56+-- | Natural constructor function. Throws a runtime error if the 'Int'
57+-- value is greater than the corresponding @m@ or lower than @n@ in the @'Natural' n m@ type.
58+nat :: forall n m . (KnownNat n, KnownNat m) => Int -> Natural n m
59+nat i =
60+ let start = fromInteger (natVal (Proxy :: Proxy n))
61+ end = fromInteger (natVal (Proxy :: Proxy m))
62+ in if start <= i && i <= end
63+ then Nat i
64+ else error "Off limits"
65+
66+-- | Auxiliary function that promotes binary 'Int' functions to 'Natural'
67+-- binary functions.
68+coerceNat :: (Int -> Int -> Int) -> (Natural a a' -> Natural b b' -> Natural c c')
69+coerceNat = coerce
70+
71+-- | Auxiliary function that promotes ternary (binary) 'Int' functions to 'Natural'
72+-- functions.
73+coerceNat2 :: ((Int, Int) -> Int -> Int) -> ((Natural a a', Natural b b') -> Natural c c' -> Natural d d')
74+coerceNat2 = coerce
75+
76+-- | Auxiliary function that promotes ternary (binary) 'Int' functions to 'Natural'
77+-- functions.
78+coerceNat3 :: (Int -> Int -> a) -> (Natural b b' -> Natural c c' -> a)
79+coerceNat3 = coerce
80+
81+instance (KnownNat n, KnownNat m) => Bounded (Natural n m) where
82+ minBound = Nat $ fromInteger (natVal (Proxy :: Proxy n))
83+ maxBound = Nat $ fromInteger (natVal (Proxy :: Proxy m))
84+
85+instance (KnownNat n, KnownNat m) => Enum (Natural n m) where
86+ toEnum i =
87+ let start = fromInteger (natVal (Proxy :: Proxy n))
88+ in nat (start + i)
89+ -- | Throws a runtime error if the value is off limits
90+ fromEnum (Nat nat) =
91+ let start = fromInteger (natVal (Proxy :: Proxy n))
92+ end = fromInteger (natVal (Proxy :: Proxy m))
93+ in if start <= nat && nat <= end
94+ then nat - start
95+ else error "Off limits"
96+
97+-- | Optimized 'Enum' instance for tuples that comply with the given
98+-- constraints.
99+instance
100+ ( Enum a,
101+ Enum b,
102+ Bounded b
103+ ) =>
104+ Enum (a, b)
105+ where
106+
107+ toEnum i =
108+ let (listB :: [b]) = [minBound .. maxBound]
109+ lengthB = length listB
110+ fstI = div i lengthB
111+ sndI = mod i lengthB
112+ in (toEnum fstI, toEnum sndI)
113+
114+ fromEnum (a, b) =
115+ let (listB :: [b]) = [minBound .. maxBound]
116+ lengthB = length listB
117+ fstI = fromEnum a
118+ sndI = fromEnum b
119+ in fstI * lengthB + sndI
120+
121+instance
122+ ( Bounded a,
123+ Bounded b
124+ ) => Bounded (Either a b)
125+ where
126+ minBound = Left (minBound :: a)
127+ maxBound = Right (maxBound :: b)
128+
129+instance
130+ ( Enum a,
131+ Bounded a,
132+ Enum b,
133+ Bounded b
134+ ) => Enum (Either a b)
135+ where
136+ toEnum i =
137+ let la = fmap Left ([minBound..maxBound] :: [a])
138+ lb = fmap Right ([minBound..maxBound] :: [b])
139+ in (la ++ lb) !! i
140+
141+ fromEnum (Left a) = fromEnum a
142+ fromEnum (Right b) = fromEnum (maxBound :: a) + fromEnum b + 1
143+
144+-- | Powerset data type.
145+--
146+-- This data type is a newtype wrapper around '[]'. This exists in order to
147+-- implement an 'Enum' and 'Bounded' instance that cannot be harmful for the outside.
148+newtype List a = L [a]
149+ deriving (Eq, Show, Read)
150+
151+powerset :: [a] -> [[a]]
152+powerset [] = [[]]
153+powerset (x:xs) = powerset xs ++ [x:ps | ps <- powerset xs]
154+
155+instance
156+ ( Enum a,
157+ Bounded a
158+ ) => Bounded (List a)
159+ where
160+ minBound = L []
161+ maxBound = L [minBound .. maxBound]
162+
163+instance
164+ ( Bounded a,
165+ Enum a,
166+ Eq a
167+ ) => Enum (List a)
168+ where
169+ toEnum i =
170+ let as = [minBound .. maxBound]
171+ in L (powerset as !! i)
172+
173+ fromEnum (L []) = 0
174+ fromEnum (L x) =
175+ let as = [minBound .. maxBound]
176+ in fromMaybe (error "Does not exist") $ elemIndex x (powerset as)
177+
178+-- | Constrained category instance
179+class Category k where
180+ type Object k o :: Constraint
181+ type Object k o = ()
182+ id :: Object k a => k a a
183+ (.) :: k b c -> k a b -> k a c
184+
185+{-# RULES
186+"identity/left" forall p .
187+ id . p = p
188+"identity/right" forall p .
189+ p . id = p
190+"association" forall p q r .
191+ (p . q) . r = p . (q . r)
192+ #-}
193+
194+instance Category (->) where
195+ id = Prelude.id
196+ (.) = (Prelude..)
src/Matrix/Internal.hsdeleted−781
@@ -1,781 +0,0 @@
1−{-# LANGUAGE AllowAmbiguousTypes #-}
2−{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE FlexibleContexts #-}
4−{-# LANGUAGE FlexibleInstances #-}
5−{-# LANGUAGE GADTs #-}
6−{-# LANGUAGE InstanceSigs #-}
7−{-# LANGUAGE MultiParamTypeClasses #-}
8−{-# LANGUAGE NoStarIsType #-}
9−{-# LANGUAGE ScopedTypeVariables #-}
10−{-# LANGUAGE StandaloneDeriving #-}
11−{-# LANGUAGE TypeApplications #-}
12−{-# LANGUAGE TypeFamilies #-}
13−{-# LANGUAGE TypeOperators #-}
14−{-# LANGUAGE UndecidableInstances #-}
15−
16−-----------------------------------------------------------------------------
17−-- |
18−-- Module : Matrix.Internal
19−-- Copyright : (c) Armando Santos 2019-2020
20−-- Maintainer : armandoifsantos@gmail.com
21−-- Stability : experimental
22−--
23−-- The LAoP discipline generalises relations and functions treating them as
24−-- Boolean matrices and in turn consider these as arrows.
25−--
26−-- __LAoP__ is a library for algebraic (inductive) construction and manipulation of matrices
27−-- in Haskell. See <https://github.com/bolt12/master-thesis my Msc Thesis> for the
28−-- motivation behind the library, the underlying theory, and implementation details.
29−--
30−-- This module offers many of the combinators mentioned in the work of
31−-- Macedo (2012) and Oliveira (2012).
32−--
33−-- This is an Internal module and it is no supposed to be imported.
34−--
35−-----------------------------------------------------------------------------
36−
37−module Matrix.Internal
38− ( -- | This definition makes use of the fact that 'Void' is
39− -- isomorphic to 0 and '()' to 1 and captures matrix
40− -- dimensions as stacks of 'Either's.
41− --
42− -- There exists two type families that make it easier to write
43− -- matrix dimensions: 'FromNat' and 'Count'. This approach
44− -- leads to a very straightforward implementation
45− -- of LAoP combinators.
46−
47− -- * Type safe matrix representation
48− Matrix (..),
49−
50− -- * Primitives
51− empty,
52− one,
53− junc,
54− split,
55−
56− -- * Auxiliary type families
57− FromNat,
58− Count,
59− Normalize,
60−
61− -- * Matrix construction and conversion
62− FromLists,
63− fromLists,
64− toLists,
65− toList,
66− matrixBuilder,
67− row,
68− col,
69− zeros,
70− ones,
71− bang,
72− constant,
73−
74− -- * Misc
75− -- ** Get dimensions
76− columns,
77− rows,
78−
79− -- ** Matrix Transposition
80− tr,
81−
82− -- ** Selective operator
83− select,
84−
85− -- ** McCarthy's Conditional
86− cond,
87−
88− -- ** Matrix "abiding"
89− abideJS,
90− abideSJ,
91−
92− -- * Biproduct approach
93− -- ** Split
94− (===),
95− -- *** Projections
96− p1,
97− p2,
98− -- ** Junc
99− (|||),
100− -- *** Injections
101− i1,
102− i2,
103− -- ** Bifunctors
104− (-|-),
105− (><),
106−
107− -- ** Applicative matrix combinators
108−
109− -- | Note that given the restrictions imposed it is not possible to
110− -- implement the standard type classes present in standard Haskell.
111− -- *** Matrix pairing projections
112− kp1,
113− kp2,
114−
115− -- *** Matrix pairing
116− khatri,
117−
118− -- * Matrix composition and lifting
119−
120− -- ** Arrow matrix combinators
121−
122− -- | Note that given the restrictions imposed it is not possible to
123− -- implement the standard type classes present in standard Haskell.
124− identity,
125− comp,
126− fromF,
127− fromF',
128−
129− -- * Matrix printing
130− pretty,
131− prettyPrint
132− )
133− where
134−
135−import Utils
136−import Data.Bool
137−import Data.Kind
138−import Data.List
139−import Data.Proxy
140−import Data.Void
141−import GHC.TypeLits
142−import Data.Type.Equality
143−import GHC.Generics
144−import Control.DeepSeq
145−import Control.Category
146−import Prelude hiding ((.))
147−
148−-- | LAoP (Linear Algebra of Programming) Inductive Matrix definition.
149−data Matrix e cols rows where
150− Empty :: Matrix e Void Void
151− One :: e -> Matrix e () ()
152− Junc :: Matrix e a rows -> Matrix e b rows -> Matrix e (Either a b) rows
153− Split :: Matrix e cols a -> Matrix e cols b -> Matrix e cols (Either a b)
154−
155−deriving instance (Show e) => Show (Matrix e cols rows)
156−
157−-- | Type family that computes the cardinality of a given type dimension.
158−--
159−-- It can also count the cardinality of custom types that implement the
160−-- 'Generic' instance.
161−type family Count (d :: Type) :: Nat where
162− Count (Natural n m) = (m - n) + 1
163− Count (Either a b) = (+) (Count a) (Count b)
164− Count (a, b) = (*) (Count a) (Count b)
165− Count (a -> b) = (^) (Count b) (Count a)
166− -- Generics
167− Count (M1 _ _ f p) = Count (f p)
168− Count (K1 _ _ _) = 1
169− Count (V1 _) = 0
170− Count (U1 _) = 1
171− Count ((:*:) a b p) = Count (a p) * Count (b p)
172− Count ((:+:) a b p) = Count (a p) + Count (b p)
173− Count d = Count (Rep d R)
174−
175−-- | Type family that computes of a given type dimension from a given natural
176−--
177−-- Thanks to Li-Yao Xia this type family is super fast.
178−type family FromNat (n :: Nat) :: Type where
179− FromNat 0 = Void
180− FromNat 1 = ()
181− FromNat n = FromNat' (Mod n 2 == 0) (FromNat (Div n 2))
182−
183−type family FromNat' (b :: Bool) (m :: Type) :: Type where
184− FromNat' 'True m = Either m m
185− FromNat' 'False m = Either () (Either m m)
186−
187−-- | Type family that normalizes the representation of a given data
188−-- structure
189−type family Normalize (d :: Type) :: Type where
190− Normalize d = FromNat (Count d)
191−
192−-- | It isn't possible to implement the 'id' function so it's
193−-- implementation is 'undefined'. However 'comp' can be and this partial
194−-- class implementation exists just to make the code more readable.
195−--
196−-- Please use 'identity' instead.
197−instance (Num e) => Category (Matrix e) where
198− id = undefined
199− (.) = comp
200−
201−instance NFData e => NFData (Matrix e cols rows) where
202− rnf Empty = ()
203− rnf (One e) = rnf e
204− rnf (Junc a b) = rnf a `seq` rnf b
205− rnf (Split a b) = rnf a `seq` rnf b
206−
207−instance Eq e => Eq (Matrix e cols rows) where
208− Empty == Empty = True
209− (One a) == (One b) = a == b
210− (Junc a b) == (Junc c d) = a == c && b == d
211− (Split a b) == (Split c d) = a == c && b == d
212− x@(Split a b) == y@(Junc c d) = x == abideJS y
213− x@(Junc a b) == y@(Split c d) = abideJS x == y
214−
215−instance Num e => Num (Matrix e cols rows) where
216−
217− Empty + Empty = Empty
218− (One a) + (One b) = One (a + b)
219− (Junc a b) + (Junc c d) = Junc (a + c) (b + d)
220− (Split a b) + (Split c d) = Split (a + c) (b + d)
221− x@(Split a b) + y@(Junc c d) = x + abideJS y
222− x@(Junc a b) + y@(Split c d) = abideJS x + y
223−
224− Empty - Empty = Empty
225− (One a) - (One b) = One (a - b)
226− (Junc a b) - (Junc c d) = Junc (a - c) (b - d)
227− (Split a b) - (Split c d) = Split (a - c) (b - d)
228− x@(Split a b) - y@(Junc c d) = x - abideJS y
229− x@(Junc a b) - y@(Split c d) = abideJS x - y
230−
231− Empty * Empty = Empty
232− (One a) * (One b) = One (a * b)
233− (Junc a b) * (Junc c d) = Junc (a * c) (b * d)
234− (Split a b) * (Split c d) = Split (a * c) (b * d)
235− x@(Split a b) * y@(Junc c d) = x * abideJS y
236− x@(Junc a b) * y@(Split c d) = abideJS x * y
237−
238− abs Empty = Empty
239− abs (One a) = One (abs a)
240− abs (Junc a b) = Junc (abs a) (abs b)
241− abs (Split a b) = Split (abs a) (abs b)
242−
243− signum Empty = Empty
244− signum (One a) = One (signum a)
245− signum (Junc a b) = Junc (signum a) (signum b)
246− signum (Split a b) = Split (signum a) (signum b)
247−
248−-- Primitives
249−
250−-- | Empty matrix constructor
251−empty :: Matrix e Void Void
252−empty = Empty
253−
254−-- | Unit matrix constructor
255−one :: e -> Matrix e () ()
256−one = One
257−
258−-- | Matrix 'Junc' constructor
259−junc :: Matrix e a rows -> Matrix e b rows -> Matrix e (Either a b) rows
260−junc = Junc
261−
262−infixl 3 |||
263−
264−-- | Matrix 'Junc' constructor
265−(|||) :: Matrix e a rows -> Matrix e b rows -> Matrix e (Either a b) rows
266−(|||) = Junc
267−
268−-- | Matrix 'Split' constructor
269−split :: Matrix e cols a -> Matrix e cols b -> Matrix e cols (Either a b)
270−split = Split
271−
272−infixl 2 ===
273−
274−-- | Matrix 'Split' constructor
275−(===) :: Matrix e cols a -> Matrix e cols b -> Matrix e cols (Either a b)
276−(===) = Split
277−
278−-- Construction
279−
280−-- | Type class for defining the 'fromList' conversion function.
281−--
282−-- Given that it is not possible to branch on types at the term level type
283−-- classes are needed bery much like an inductive definition but on types.
284−class FromLists e cols rows where
285− -- | Build a matrix out of a list of list of elements. Throws a runtime
286− -- error if the dimensions do not match.
287− fromLists :: [[e]] -> Matrix e cols rows
288−
289−instance FromLists e Void Void where
290− fromLists [] = Empty
291− fromLists _ = error "Wrong dimensions"
292−
293−instance {-# OVERLAPPING #-} FromLists e () () where
294− fromLists [[e]] = One e
295− fromLists _ = error "Wrong dimensions"
296−
297−instance {-# OVERLAPPING #-} (FromLists e cols ()) => FromLists e (Either () cols) () where
298− fromLists [h : t] = Junc (One h) (fromLists [t])
299− fromLists _ = error "Wrong dimensions"
300−
301−instance {-# OVERLAPPABLE #-} (FromLists e a (), FromLists e b (), KnownNat (Count a)) => FromLists e (Either a b) () where
302− fromLists [l] =
303− let rowsA = fromInteger (natVal (Proxy :: Proxy (Count a)))
304− in Junc (fromLists [take rowsA l]) (fromLists [drop rowsA l])
305− fromLists _ = error "Wrong dimensions"
306−
307−instance {-# OVERLAPPING #-} (FromLists e () rows) => FromLists e () (Either () rows) where
308− fromLists ([h] : t) = Split (One h) (fromLists t)
309− fromLists _ = error "Wrong dimensions"
310−
311−instance {-# OVERLAPPABLE #-} (FromLists e () a, FromLists e () b, KnownNat (Count a)) => FromLists e () (Either a b) where
312− fromLists l@([h] : t) =
313− let rowsA = fromInteger (natVal (Proxy :: Proxy (Count a)))
314− in Split (fromLists (take rowsA l)) (fromLists (drop rowsA l))
315− fromLists _ = error "Wrong dimensions"
316−
317−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
318− fromLists l@(h : t) =
319− let lh = length h
320− rowsC = fromInteger (natVal (Proxy :: Proxy (Count c)))
321− condition = all (== lh) (map length t)
322− in if lh > 0 && condition
323− then Split (fromLists (take rowsC l)) (fromLists (drop rowsC l))
324− else error "Not all rows have the same length"
325−
326−-- | Matrix builder function. Constructs a matrix provided with
327−-- a construction function.
328−matrixBuilder ::
329− forall e cols rows.
330− ( FromLists e cols rows,
331− KnownNat (Count cols),
332− KnownNat (Count rows)
333− ) =>
334− ((Int, Int) -> e) ->
335− Matrix e cols rows
336−matrixBuilder f =
337− let c = fromInteger $ natVal (Proxy :: Proxy (Count cols))
338− r = fromInteger $ natVal (Proxy :: Proxy (Count rows))
339− positions = [(a, b) | a <- [0 .. (r - 1)], b <- [0 .. (c - 1)]]
340− in fromLists . map (map f) . groupBy (\(x, _) (w, _) -> x == w) $ positions
341−
342−-- | Constructs a column vector matrix
343−col :: (FromLists e () rows) => [e] -> Matrix e () rows
344−col = fromLists . map (: [])
345−
346−-- | Constructs a row vector matrix
347−row :: (FromLists e cols ()) => [e] -> Matrix e cols ()
348−row = fromLists . (: [])
349−
350−-- | Lifts functions to matrices with arbitrary dimensions.
351−--
352−-- NOTE: Be careful to not ask for a matrix bigger than the cardinality of
353−-- types @a@ or @b@ allows.
354−fromF ::
355− forall a b cols rows e.
356− ( Bounded a,
357− Bounded b,
358− Enum a,
359− Enum b,
360− Eq b,
361− Num e,
362− Ord e,
363− KnownNat (Count cols),
364− KnownNat (Count rows),
365− FromLists e rows cols
366− ) =>
367− (a -> b) ->
368− Matrix e cols rows
369−fromF f =
370− let minA = minBound @a
371− maxA = maxBound @a
372− minB = minBound @b
373− maxB = maxBound @b
374− ccols = fromInteger $ natVal (Proxy :: Proxy (Count cols))
375− rrows = fromInteger $ natVal (Proxy :: Proxy (Count rows))
376− elementsA = take ccols [minA .. maxA]
377− elementsB = take rrows [minB .. maxB]
378− combinations = (,) <$> elementsA <*> elementsB
379− combAp = map snd . sort . map (\(a, b) -> if f a == b
380− then ((fromEnum a, fromEnum b), 1)
381− else ((fromEnum a, fromEnum b), 0)) $ combinations
382− mList = buildList combAp rrows
383− in tr $ fromLists mList
384− where
385− buildList [] _ = []
386− buildList l r = take r l : buildList (drop r l) r
387−
388−-- | Lifts functions to matrices with dimensions matching @a@ and @b@
389−-- cardinality's.
390−fromF' ::
391− forall a b e.
392− ( Bounded a,
393− Bounded b,
394− Enum a,
395− Enum b,
396− Eq b,
397− Num e,
398− Ord e,
399− KnownNat (Count (Normalize a)),
400− KnownNat (Count (Normalize b)),
401− FromLists e (Normalize b) (Normalize a)
402− ) =>
403− (a -> b) ->
404− Matrix e (Normalize a) (Normalize b)
405−fromF' f =
406− let minA = minBound @a
407− maxA = maxBound @a
408− minB = minBound @b
409− maxB = maxBound @b
410− ccols = fromInteger $ natVal (Proxy :: Proxy (Count (Normalize a)))
411− rrows = fromInteger $ natVal (Proxy :: Proxy (Count (Normalize b)))
412− elementsA = take ccols [minA .. maxA]
413− elementsB = take rrows [minB .. maxB]
414− combinations = (,) <$> elementsA <*> elementsB
415− combAp = map snd . sort . map (\(a, b) -> if f a == b
416− then ((fromEnum a, fromEnum b), 1)
417− else ((fromEnum a, fromEnum b), 0)) $ combinations
418− mList = buildList combAp rrows
419− in tr $ fromLists mList
420− where
421− buildList [] _ = []
422− buildList l r = take r l : buildList (drop r l) r
423−
424−-- Conversion
425−
426−-- | Converts a matrix to a list of lists of elements.
427−toLists :: Matrix e cols rows -> [[e]]
428−toLists Empty = []
429−toLists (One e) = [[e]]
430−toLists (Split l r) = toLists l ++ toLists r
431−toLists (Junc l r) = zipWith (++) (toLists l) (toLists r)
432−
433−-- | Converts a matrix to a list of elements.
434−toList :: Matrix e cols rows -> [e]
435−toList = concat . toLists
436−
437−-- Zeros Matrix
438−
439−-- | The zero matrix. A matrix wholly filled with zeros.
440−zeros :: (Num e, FromLists e cols rows, KnownNat (Count cols), KnownNat (Count rows)) => Matrix e cols rows
441−zeros = matrixBuilder (const 0)
442−
443−-- Ones Matrix
444−
445−-- | The ones matrix. A matrix wholly filled with ones.
446−--
447−-- Also known as T (Top) matrix.
448−ones :: (Num e, FromLists e cols rows, KnownNat (Count cols), KnownNat (Count rows)) => Matrix e cols rows
449−ones = matrixBuilder (const 1)
450−
451−-- Const Matrix
452−
453−-- | The constant matrix constructor. A matrix wholly filled with a given
454−-- value.
455−constant :: (Num e, FromLists e cols rows, KnownNat (Count cols), KnownNat (Count rows)) => e -> Matrix e cols rows
456−constant e = matrixBuilder (const e)
457−
458−-- Bang Matrix
459−
460−-- | The T (Top) row vector matrix.
461−bang :: forall e cols. (Num e, Enum e, FromLists e cols (), KnownNat (Count cols)) => Matrix e cols ()
462−bang =
463− let c = fromInteger $ natVal (Proxy :: Proxy (Count cols))
464− in fromLists [take c [1, 1 ..]]
465−
466−-- Identity Matrix
467−
468−-- | Identity matrix.
469−identity :: (Num e, FromLists e cols cols, KnownNat (Count cols)) => Matrix e cols cols
470−identity = matrixBuilder (bool 0 1 . uncurry (==))
471−
472−-- Matrix composition (MMM)
473−
474−-- | Matrix composition. Equivalent to matrix-matrix multiplication.
475−--
476−-- This definition takes advantage of divide-and-conquer and fusion laws
477−-- from LAoP.
478−comp :: (Num e) => Matrix e cr rows -> Matrix e cols cr -> Matrix e cols rows
479−comp Empty Empty = Empty
480−comp (One a) (One b) = One (a * b)
481−comp (Junc a b) (Split c d) = comp a c + comp b d -- Divide-and-conquer law
482−comp (Split a b) c = Split (comp a c) (comp b c) -- Split fusion law
483−comp c (Junc a b) = Junc (comp c a) (comp c b) -- Junc fusion law
484−
485−-- Projections
486−
487−-- | Biproduct first component projection
488−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
489−p1 =
490− let iden = identity :: Matrix e m m
491− zero = zeros :: Matrix e n m
492− in junc iden zero
493−
494−-- | Biproduct second component projection
495−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
496−p2 =
497− let iden = identity :: Matrix e n n
498− zero = zeros :: Matrix e m n
499− in junc zero iden
500−
501−-- Injections
502−
503−-- | Biproduct first component injection
504−i1 :: (Num e, KnownNat (Count n), KnownNat (Count m), FromLists e n m, FromLists e m m) => Matrix e m (Either m n)
505−i1 = tr p1
506−
507−-- | Biproduct second component injection
508−i2 :: (Num e, KnownNat (Count n), KnownNat (Count m), FromLists e m n, FromLists e n n) => Matrix e n (Either m n)
509−i2 = tr p2
510−
511−-- Dimensions
512−
513−-- | Obtain the number of rows.
514−--
515−-- NOTE: The 'KnownNat' constaint is needed in order to obtain the
516−-- dimensions in constant time.
517−--
518−-- TODO: A 'rows' function that does not need the 'KnownNat' constraint in
519−-- exchange for performance.
520−rows :: forall e cols rows. (KnownNat (Count rows)) => Matrix e cols rows -> Int
521−rows _ = fromInteger $ natVal (Proxy :: Proxy (Count rows))
522−
523−-- | Obtain the number of columns.
524−--
525−-- NOTE: The 'KnownNat' constaint is needed in order to obtain the
526−-- dimensions in constant time.
527−--
528−-- TODO: A 'columns' function that does not need the 'KnownNat' constraint in
529−-- exchange for performance.
530−columns :: forall e cols rows. (KnownNat (Count cols)) => Matrix e cols rows -> Int
531−columns _ = fromInteger $ natVal (Proxy :: Proxy (Count cols))
532−
533−-- Coproduct Bifunctor
534−
535−infixl 5 -|-
536−
537−-- | Matrix coproduct functor also known as matrix direct sum.
538−(-|-) ::
539− forall e n k m j.
540− ( Num e,
541− KnownNat (Count j),
542− KnownNat (Count k),
543− FromLists e k k,
544− FromLists e j k,
545− FromLists e k j,
546− FromLists e j j
547− ) =>
548− Matrix e n k ->
549− Matrix e m j ->
550− Matrix e (Either n m) (Either k j)
551−(-|-) a b = Junc (i1 . a) (i2 . b)
552−
553−-- Khatri Rao Product and projections
554−
555−-- | Khatri Rao product first component projection matrix.
556−kp1 ::
557− forall e m k .
558− ( Num e,
559− KnownNat (Count k),
560− FromLists e (FromNat (Count m * Count k)) m,
561− KnownNat (Count m),
562− KnownNat (Count (Normalize (m, k)))
563− ) => Matrix e (Normalize (m, k)) m
564−kp1 = matrixBuilder f
565− where
566− offset = fromInteger (natVal (Proxy :: Proxy (Count k)))
567− f (x, y)
568− | y >= (x * offset) && y <= (x * offset + offset - 1) = 1
569− | otherwise = 0
570−
571−-- | Khatri Rao product second component projection matrix.
572−kp2 ::
573− forall e m k .
574− ( Num e,
575− KnownNat (Count k),
576− FromLists e (FromNat (Count m * Count k)) k,
577− KnownNat (Count m),
578− KnownNat (Count (Normalize (m, k)))
579− ) => Matrix e (Normalize (m, k)) k
580−kp2 = matrixBuilder f
581− where
582− offset = fromInteger (natVal (Proxy :: Proxy (Count k)))
583− f (x, y)
584− | x == y || mod (y - x) offset == 0 = 1
585− | otherwise = 0
586−
587−-- | Khatri Rao Matrix product also known as matrix pairing.
588−--
589−-- NOTE: That this is not a true categorical product, see for instance:
590−--
591−-- @
592−-- | kp1 . khatri a b == a
593−-- khatri a b ==> |
594−-- | kp2 . khatri a b == b
595−-- @
596−--
597−-- __Emphasis__ on the implication symbol.
598−khatri ::
599− forall e cols a b.
600− ( Num e,
601− KnownNat (Count a),
602− KnownNat (Count b),
603− KnownNat (Count (Normalize (a, b))),
604− FromLists e (Normalize (a, b)) a,
605− FromLists e (Normalize (a, b)) b
606− ) => Matrix e cols a -> Matrix e cols b -> Matrix e cols (Normalize (a, b))
607−khatri a b =
608− let kp1' = kp1 @e @a @b
609− kp2' = kp2 @e @a @b
610− in (tr kp1') . a * (tr kp2') . b
611−
612−-- Product Bifunctor (Kronecker)
613−
614−infixl 4 ><
615−
616−-- | Matrix product functor also known as kronecker product
617−(><) ::
618− forall e m p n q.
619− ( Num e,
620− KnownNat (Count m),
621− KnownNat (Count n),
622− KnownNat (Count p),
623− KnownNat (Count q),
624− KnownNat (Count (Normalize (m, n))),
625− FromLists e (Normalize (m, n)) m,
626− FromLists e (Normalize (m, n)) n,
627− KnownNat (Count (Normalize (p, q))),
628− FromLists e (Normalize (p, q)) p,
629− FromLists e (Normalize (p, q)) q
630− )
631− => Matrix e m p -> Matrix e n q -> Matrix e (Normalize (m, n)) (Normalize (p, q))
632−(><) a b =
633− let kp1' = kp1 @e @m @n
634− kp2' = kp2 @e @m @n
635− in khatri (a . kp1') (b . kp2')
636−
637−-- Matrix abide Junc Split
638−
639−-- | Matrix "abiding" followin the 'Junc'-'Split' abide law.
640−--
641−-- Law:
642−--
643−-- @
644−-- 'Junc' ('Split' a c) ('Split' b d) == 'Split' ('Junc' a b) ('Junc' c d)
645−-- @
646−abideJS :: Matrix e cols rows -> Matrix e cols rows
647−abideJS (Junc (Split a c) (Split b d)) = Split (Junc (abideJS a) (abideJS b)) (Junc (abideJS c) (abideJS d)) -- Junc-Split abide law
648−abideJS Empty = Empty
649−abideJS (One e) = One e
650−abideJS (Junc a b) = Junc (abideJS a) (abideJS b)
651−abideJS (Split a b) = Split (abideJS a) (abideJS b)
652−
653−-- Matrix abide Split Junc
654−
655−-- | Matrix "abiding" followin the 'Split'-'Junc' abide law.
656−--
657−-- @
658−-- 'Split' ('Junc' a b) ('Junc' c d) == 'Junc' ('Split' a c) ('Split' b d)
659−-- @
660−abideSJ :: Matrix e cols rows -> Matrix e cols rows
661−abideSJ (Split (Junc a b) (Junc c d)) = Junc (Split (abideSJ a) (abideSJ c)) (Split (abideSJ b) (abideSJ d)) -- Split-Junc abide law
662−abideSJ Empty = Empty
663−abideSJ (One e) = One e
664−abideSJ (Junc a b) = Junc (abideSJ a) (abideSJ b)
665−abideSJ (Split a b) = Split (abideSJ a) (abideSJ b)
666−
667−-- Matrix transposition
668−
669−-- | Matrix transposition.
670−tr :: Matrix e cols rows -> Matrix e rows cols
671−tr Empty = Empty
672−tr (One e) = One e
673−tr (Junc a b) = Split (tr a) (tr b)
674−tr (Split a b) = Junc (tr a) (tr b)
675−
676−-- Selective 'select' operator
677−
678−-- | Selective functors 'select' operator equivalent inspired by the
679−-- ArrowMonad solution presented in the paper.
680−select ::
681− ( Bounded a,
682− Bounded b,
683− Enum a,
684− Enum b,
685− Num e,
686− Ord e,
687− Eq b,
688− KnownNat (Count (Normalize a)),
689− KnownNat (Count (Normalize b)),
690− KnownNat (Count cols),
691− FromLists e (Normalize b) (Normalize a),
692− FromLists e (Normalize b) (Normalize b)
693− ) => Matrix e cols (Either (Normalize a) (Normalize b)) -> (a -> b) -> Matrix e cols (Normalize b)
694−select m y =
695− let f = fromF y
696− in junc f identity . m
697−
698−-- McCarthy's Conditional
699−
700−-- | McCarthy's Conditional expresses probabilistic choice.
701−cond ::
702− ( cols ~ FromNat (Count cols),
703− KnownNat (Count cols),
704− FromLists e () cols,
705− FromLists e cols (),
706− FromLists e cols cols,
707− Bounded a,
708− Enum a,
709− Num e,
710− Ord e
711− )
712− =>
713− (a -> Bool) -> Matrix e cols rows -> Matrix e cols rows -> Matrix e cols rows
714−cond p f g = junc f g . grd p
715−
716−grd ::
717− ( q ~ FromNat (Count q),
718− KnownNat (Count q),
719− FromLists e () q,
720− FromLists e q (),
721− FromLists e q q,
722− Bounded a,
723− Enum a,
724− Num e,
725− Ord e
726− )
727− =>
728− (a -> Bool) -> Matrix e q (Either q q)
729−grd f = split (corr f) (corr (not . f))
730−
731−corr ::
732− forall e a q .
733− ( q ~ FromNat (Count q),
734− KnownNat (Count q),
735− FromLists e () q,
736− FromLists e q (),
737− FromLists e q q,
738− Bounded a,
739− Enum a,
740− Num e,
741− Ord e
742− )
743− => (a -> Bool) -> Matrix e q q
744−corr p = let f = fromF p :: Matrix e q ()
745− in khatri f (identity :: Matrix e q q)
746−
747−-- Pretty print
748−
749−prettyAux :: Show e => [[e]] -> [[e]] -> String
750−prettyAux [] _ = ""
751−prettyAux [[e]] m = "│ " ++ fill (show e) ++ " │\n"
752− where
753− v = fmap show m
754− widest = maximum $ fmap length v
755− fill str = replicate (widest - length str - 2) ' ' ++ str
756−prettyAux [h] m = "│ " ++ fill (unwords $ map show h) ++ " │\n"
757− where
758− v = fmap show m
759− widest = maximum $ fmap length v
760− fill str = replicate (widest - length str - 2) ' ' ++ str
761−prettyAux (h : t) l = "│ " ++ fill (unwords $ map show h) ++ " │\n" ++
762− prettyAux t l
763− where
764− v = fmap show l
765− widest = maximum $ fmap length v
766− fill str = replicate (widest - length str - 2) ' ' ++ str
767−
768−-- | Matrix pretty printer
769−pretty :: (KnownNat (Count cols), Show e) => Matrix e cols rows -> String
770−pretty m = "┌ " ++ unwords (replicate (columns m) blank) ++ " ┐\n" ++
771− prettyAux (toLists m) (toLists m) ++
772− "└ " ++ unwords (replicate (columns m) blank) ++ " ┘"
773− where
774− v = fmap show (toList m)
775− widest = maximum $ fmap length v
776− fill str = replicate (widest - length str) ' ' ++ str
777− blank = fill ""
778−
779−-- | Matrix pretty printer
780−prettyPrint :: (KnownNat (Count cols), Show e) => Matrix e cols rows -> IO ()
781−prettyPrint = putStrLn . pretty
src/Matrix/Nat.hsdeleted−488
@@ -1,488 +0,0 @@
1−{-# LANGUAGE AllowAmbiguousTypes #-}
2−{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE DerivingVia #-}
4−{-# LANGUAGE FlexibleContexts #-}
5−{-# LANGUAGE FlexibleInstances #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE KindSignatures #-}
8−{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE NoStarIsType #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TypeApplications #-}
13−{-# LANGUAGE TypeOperators #-}
14−{-# LANGUAGE UndecidableInstances #-}
15−
16−-----------------------------------------------------------------------------
17−-- |
18−-- Module : Matrix.Nat
19−-- Copyright : (c) Armando Santos 2019-2020
20−-- Maintainer : armandoifsantos@gmail.com
21−-- Stability : experimental
22−--
23−-- The LAoP discipline generalises relations and functions treating them as
24−-- Boolean matrices and in turn consider these as arrows.
25−--
26−-- __LAoP__ is a library for algebraic (inductive) construction and manipulation of matrices
27−-- in Haskell. See <https://github.com/bolt12/master-thesis my Msc Thesis> for the
28−-- motivation behind the library, the underlying theory, and implementation details.
29−--
30−-- This module offers a newtype wrapper around 'Matrix.Type.Matrix' that
31−-- uses type level naturals instead of standard data types for the matrices
32−-- dimensions.
33−--
34−-----------------------------------------------------------------------------
35−
36−module Matrix.Nat
37− ( -- | LAoP (Linear Algebra of Programming) Inductive Matrix definition.
38− --
39− -- LAoP generalises relations and functions treating them as
40− -- Boolean matrices and in turn consider these as arrows.
41− -- This library offers many of the combinators mentioned in the work of
42− -- Macedo (2012) and Oliveira (2012).
43− --
44− -- This definition is a wrapper around 'Matrix.Type' but
45− -- dimensions are type level Naturals. Type inference might not
46− -- be as desired.
47− --
48− -- There exists two type families that make it easier to write
49− -- matrix dimensions: 'FromNat' and 'Count'. This approach
50− -- leads to a very straightforward implementation
51− -- of LAoP combinators.
52−
53− -- * Type safe matrix representation
54− Matrix (..),
55−
56− -- * Primitives
57− empty,
58− one,
59− junc,
60− split,
61−
62− -- * Auxiliary type families
63− I.FromNat,
64− I.Count,
65− I.Normalize,
66−
67− -- * Matrix construction and conversion
68− I.FromLists,
69− fromLists,
70− toLists,
71− toList,
72− matrixBuilder,
73− row,
74− col,
75− zeros,
76− ones,
77− bang,
78− constant,
79−
80− -- * Misc
81− -- ** Get dimensions
82− columns,
83− rows,
84−
85− -- ** Matrix Transposition
86− tr,
87−
88− -- ** Selective operator
89− select,
90−
91− -- ** McCarthy's Conditional
92− cond,
93−
94− -- ** Matrix "abiding"
95− abideJS,
96− abideSJ,
97−
98− -- * Biproduct approach
99− -- ** Split
100− (===),
101− -- *** Projections
102− p1,
103− p2,
104− -- ** Junc
105− (|||),
106− -- *** Injections
107− i1,
108− i2,
109− -- ** Bifunctors
110− (-|-),
111− (><),
112−
113− -- ** Applicative matrix combinators
114−
115− -- | Note that given the restrictions imposed it is not possible to
116− -- implement the standard type classes present in standard Haskell.
117− -- *** Matrix pairing projections
118− kp1,
119− kp2,
120−
121− -- *** Matrix pairing
122− khatri,
123−
124− -- * Matrix composition and lifting
125−
126− -- ** Arrow matrix combinators
127−
128− -- | Note that given the restrictions imposed it is not possible to
129− -- implement the standard type classes present in standard Haskell.
130− identity,
131− comp,
132− fromF,
133− fromF',
134−
135− -- * Matrix printing
136− pretty,
137− prettyPrint
138− )
139−where
140−
141−import Data.Proxy
142−import GHC.TypeLits
143−import Control.DeepSeq
144−import qualified Control.Category as C
145−import qualified Matrix.Internal as I
146−
147−newtype Matrix e (cols :: Nat) (rows :: Nat) = M (I.Matrix e (I.FromNat cols) (I.FromNat rows))
148− deriving (Show, Num, Eq, NFData) via (I.Matrix e (I.FromNat cols) (I.FromNat rows))
149−
150−-- | It isn't possible to implement the 'id' function so it's
151−-- implementation is 'undefined'. However 'comp' can be and this partial
152−-- class implementation exists just to make the code more readable.
153−--
154−-- Please use 'identity' instead.
155−instance (Num e) => C.Category (Matrix e) where
156− id = undefined
157− (.) = comp
158−
159−-- Primitives
160−
161−empty :: Matrix e 0 0
162−empty = M I.Empty
163−
164−one :: e -> Matrix e 1 1
165−one = M . I.One
166−
167−junc ::
168− (I.FromNat cols3 ~ Either (I.FromNat cols1) (I.FromNat cols2)) =>
169− Matrix e cols1 rows ->
170− Matrix e cols2 rows ->
171− Matrix e cols3 rows
172−junc (M a) (M b) = M (I.Junc a b)
173−
174−infixl 3 |||
175−(|||) ::
176− (I.FromNat cols3 ~ Either (I.FromNat cols1) (I.FromNat cols2)) =>
177− Matrix e cols1 rows ->
178− Matrix e cols2 rows ->
179− Matrix e cols3 rows
180−(|||) = junc
181−
182−split ::
183− (I.FromNat rows3 ~ Either (I.FromNat rows1) (I.FromNat rows2)) =>
184− Matrix e cols rows1 ->
185− Matrix e cols rows2 ->
186− Matrix e cols rows3
187−split (M a) (M b) = M (I.Split a b)
188−
189−infixl 2 ===
190−(===) ::
191− (I.FromNat rows3 ~ Either (I.FromNat rows1) (I.FromNat rows2)) =>
192− Matrix e cols rows1 ->
193− Matrix e cols rows2 ->
194− Matrix e cols rows3
195−(===) = split
196−
197−-- Construction
198−
199−fromLists :: (I.FromLists e (I.FromNat cols) (I.FromNat rows)) => [[e]] -> Matrix e cols rows
200−fromLists = M . I.fromLists
201−
202−matrixBuilder ::
203− (I.FromLists e (I.FromNat cols) (I.FromNat rows), KnownNat (I.Count (I.FromNat cols)), KnownNat (I.Count (I.FromNat rows))) =>
204− ((Int, Int) -> e) ->
205− Matrix e cols rows
206−matrixBuilder = M . I.matrixBuilder
207−
208−col :: (I.FromLists e () (I.FromNat rows)) => [e] -> Matrix e 1 rows
209−col = M . I.col
210−
211−row :: (I.FromLists e (I.FromNat cols) ()) => [e] -> Matrix e cols 1
212−row = M . I.row
213−
214−fromF ::
215− ( Bounded a,
216− Bounded b,
217− Enum a,
218− Enum b,
219− Eq b,
220− Num e,
221− Ord e,
222− KnownNat (I.Count (I.FromNat cols)),
223− KnownNat (I.Count (I.FromNat rows)),
224− I.FromLists e (I.FromNat rows) (I.FromNat cols)
225− ) =>
226− (a -> b) ->
227− Matrix e cols rows
228−fromF = M . I.fromF
229−
230−fromF' ::
231− ( Bounded a,
232− Bounded b,
233− Enum a,
234− Enum b,
235− Eq b,
236− Num e,
237− Ord e,
238− KnownNat (I.Count (I.Normalize a)),
239− KnownNat (I.Count (I.Normalize b)),
240− I.FromLists e (I.Normalize b) (I.Normalize a)
241− ) =>
242− (a -> b) ->
243− Matrix e (I.Count a) (I.Count b)
244−fromF' = M . I.fromF'
245−
246−-- Conversion
247−
248−toLists :: Matrix e cols rows -> [[e]]
249−toLists (M m) = I.toLists m
250−
251−toList :: Matrix e cols rows -> [e]
252−toList (M m) = I.toList m
253−
254−-- Zeros Matrix
255−
256−zeros ::
257− (Num e, I.FromLists e (I.FromNat cols) (I.FromNat rows), KnownNat (I.Count (I.FromNat cols)), KnownNat (I.Count (I.FromNat rows))) =>
258− Matrix e cols rows
259−zeros = M I.zeros
260−
261−-- Ones Matrix
262−
263−ones ::
264− (Num e, I.FromLists e (I.FromNat cols) (I.FromNat rows), KnownNat (I.Count (I.FromNat cols)), KnownNat (I.Count (I.FromNat rows))) =>
265− Matrix e cols rows
266−ones = M I.ones
267−
268−-- Const Matrix
269−
270−constant ::
271− (Num e, I.FromLists e (I.FromNat cols) (I.FromNat rows), KnownNat (I.Count (I.FromNat cols)), KnownNat (I.Count (I.FromNat rows))) =>
272− e ->
273− Matrix e cols rows
274−constant = M . I.constant
275−
276−-- Bang Matrix
277−
278−bang ::
279− forall e cols.
280− (Num e, Enum e, I.FromLists e (I.FromNat cols) (), KnownNat (I.Count (I.FromNat cols))) =>
281− Matrix e cols 1
282−bang = M I.bang
283−
284−-- Identity Matrix
285−
286−identity ::
287− (Num e, I.FromLists e (I.FromNat cols) (I.FromNat cols), KnownNat (I.Count (I.FromNat cols))) =>
288− Matrix e cols cols
289−identity = M I.identity
290−
291−-- Matrix composition (MMM)
292−
293−comp :: (Num e) => Matrix e cr rows -> Matrix e cols cr -> Matrix e cols rows
294−comp (M a) (M b) = M (I.comp a b)
295−
296−p1 ::
297− ( Num e,
298− KnownNat (I.Count (I.FromNat n)),
299− KnownNat (I.Count (I.FromNat m)),
300− I.FromLists e (I.FromNat n) (I.FromNat m),
301− I.FromLists e (I.FromNat m) (I.FromNat m),
302− I.FromNat (m + n) ~ Either (I.FromNat m) (I.FromNat n)
303− ) =>
304− Matrix e (m + n) m
305−p1 = M I.p1
306−
307−p2 ::
308− ( Num e,
309− KnownNat (I.Count (I.FromNat n)),
310− KnownNat (I.Count (I.FromNat m)),
311− I.FromLists e (I.FromNat m) (I.FromNat n),
312− I.FromLists e (I.FromNat n) (I.FromNat n),
313− I.FromNat (m + n) ~ Either (I.FromNat m) (I.FromNat n)
314− ) =>
315− Matrix e (m + n) n
316−p2 = M I.p2
317−
318−-- Injections
319−
320−i1 ::
321− ( Num e,
322− KnownNat (I.Count (I.FromNat n)),
323− KnownNat (I.Count (I.FromNat rows)),
324− I.FromLists e (I.FromNat n) (I.FromNat rows),
325− I.FromLists e (I.FromNat rows) (I.FromNat rows),
326− I.FromNat (rows + n) ~ Either (I.FromNat rows) (I.FromNat n)
327− ) =>
328− Matrix e rows (rows + n)
329−i1 = tr p1
330−
331−i2 ::
332− ( Num e,
333− KnownNat (I.Count (I.FromNat rows)),
334− KnownNat (I.Count (I.FromNat m)),
335− I.FromLists e (I.FromNat m) (I.FromNat rows),
336− I.FromLists e (I.FromNat rows) (I.FromNat rows),
337− I.FromNat (m + rows) ~ Either (I.FromNat m) (I.FromNat rows)
338− ) =>
339− Matrix e rows (m + rows)
340−i2 = tr p2
341−
342−-- Dimensions
343−
344−rows :: (KnownNat (I.Count (I.FromNat rows))) => Matrix e cols rows -> Int
345−rows (M m) = I.rows m
346−
347−columns :: (KnownNat (I.Count (I.FromNat cols))) => Matrix e cols rows -> Int
348−columns (M m) = I.columns m
349−
350−-- Coproduct Bifunctor
351−
352−infixl 5 -|-
353−
354−(-|-) ::
355− ( Num e,
356− KnownNat (I.Count (I.FromNat j)),
357− KnownNat (I.Count (I.FromNat k)),
358− I.FromLists e (I.FromNat k) (I.FromNat k),
359− I.FromLists e (I.FromNat j) (I.FromNat k),
360− I.FromLists e (I.FromNat k) (I.FromNat j),
361− I.FromLists e (I.FromNat j) (I.FromNat j),
362− I.FromNat (n + m) ~ Either (I.FromNat n) (I.FromNat m),
363− I.FromNat (k + j) ~ Either (I.FromNat k) (I.FromNat j)
364− ) =>
365− Matrix e n k ->
366− Matrix e m j ->
367− Matrix e (n + m) (k + j)
368−(-|-) (M a) (M b) = M ((I.-|-) a b)
369−
370−-- Khatri Rao Product and projections
371−
372−kp1 ::
373− forall e m k .
374− ( Num e,
375− KnownNat (I.Count (I.FromNat m)),
376− KnownNat (I.Count (I.FromNat k)),
377− KnownNat (I.Count (I.FromNat (m * k))),
378− I.FromLists e (I.FromNat (m * k)) (I.FromNat m),
379− I.FromNat (m * k) ~ I.FromNat (I.Count (I.FromNat m) * I.Count (I.FromNat k))
380− ) => Matrix e (m * k) m
381−kp1 = M (I.kp1 @e @(I.FromNat m) @(I.FromNat k))
382−
383−kp2 ::
384− forall e m k.
385− ( Num e,
386− KnownNat (I.Count (I.FromNat k)),
387− I.FromLists e (I.FromNat (m * k)) (I.FromNat k),
388− KnownNat (I.Count (I.FromNat m)),
389− KnownNat (I.Count (I.FromNat (m * k))),
390− I.FromNat (m * k) ~ I.FromNat (I.Count (I.FromNat m) * I.Count (I.FromNat k))
391− ) => Matrix e (m * k) k
392−kp2 = M (I.kp2 @e @(I.FromNat m) @(I.FromNat k))
393−
394−khatri ::
395− forall e cols a b.
396− ( Num e,
397− KnownNat (I.Count (I.FromNat a)),
398− KnownNat (I.Count (I.FromNat b)),
399− KnownNat (I.Count (I.FromNat (a * b))),
400− I.FromLists e (I.FromNat (a * b)) (I.FromNat a),
401− I.FromLists e (I.FromNat (a * b)) (I.FromNat b),
402− I.FromNat (a * b) ~ I.FromNat (I.Count (I.FromNat a) * I.Count (I.FromNat b))
403− ) => Matrix e cols a -> Matrix e cols b -> Matrix e cols (a * b)
404−khatri a b =
405− let kp1' = kp1 @e @a @b
406− kp2' = kp2 @e @a @b
407− in comp (tr kp1') a * comp (tr kp2') b
408−
409−-- Product Bifunctor (Kronecker)
410−
411−infixl 4 ><
412−
413−(><) ::
414− forall e m p n q.
415− ( Num e,
416− KnownNat (I.Count (I.FromNat m)),
417− KnownNat (I.Count (I.FromNat n)),
418− KnownNat (I.Count (I.FromNat p)),
419− KnownNat (I.Count (I.FromNat q)),
420− KnownNat (I.Count (I.FromNat (m * n))),
421− KnownNat (I.Count (I.FromNat (p * q))),
422− I.FromLists e (I.FromNat (m * n)) (I.FromNat m),
423− I.FromLists e (I.FromNat (m * n)) (I.FromNat n),
424− I.FromLists e (I.FromNat (p * q)) (I.FromNat p),
425− I.FromLists e (I.FromNat (p * q)) (I.FromNat q),
426− I.FromNat (m * n) ~ I.FromNat (I.Count (I.FromNat m) * I.Count (I.FromNat n)),
427− I.FromNat (p * q) ~ I.FromNat (I.Count (I.FromNat p) * I.Count (I.FromNat q))
428− ) => Matrix e m p -> Matrix e n q -> Matrix e (m * n) (p * q)
429−(><) a b =
430− let kp1' = kp1 @e @m @n
431− kp2' = kp2 @e @m @n
432− in khatri (comp a kp1') (comp b kp2')
433−
434−-- Matrix abide Junc Split
435−
436−abideJS :: Matrix e cols rows -> Matrix e cols rows
437−abideJS (M m) = M (I.abideJS m)
438−
439−-- Matrix abide Split Junc
440−
441−abideSJ :: Matrix e cols rows -> Matrix e cols rows
442−abideSJ (M m) = M (I.abideSJ m)
443−
444−-- Matrix transposition
445−
446−tr :: Matrix e cols rows -> Matrix e rows cols
447−tr (M m) = M (I.tr m)
448−
449−-- Selective 'select' operator
450−--
451−select :: (Bounded a, Bounded b, Enum a, Enum b, Num e, Ord e,
452− KnownNat (I.Count (I.FromNat (I.Count a))),
453− KnownNat (I.Count (I.FromNat (I.Count b))),
454− KnownNat (I.Count (I.FromNat cols1)),
455− I.FromLists e (I.FromNat (I.Count b)) (I.FromNat (I.Count a)),
456− I.FromLists e (I.FromNat (I.Count b)) (I.FromNat (I.Count b)),
457− Eq b,
458− I.FromNat rows1
459− ~ Either (I.FromNat (I.Count a)) (I.FromNat (I.Count b)),
460− I.FromNat cols2 ~ I.FromNat cols1,
461− I.FromNat (I.Count b) ~ I.FromNat rows2) =>
462− Matrix e cols1 rows1 -> (a -> b) -> Matrix e cols2 rows2
463−select (M m) y = M (I.select m y)
464−
465−-- McCarthy's Conditional
466−
467−cond ::
468− ( I.FromNat (I.Count (I.FromNat cols)) ~ I.FromNat cols,
469− KnownNat (I.Count (I.FromNat cols)),
470− I.FromLists e () (I.FromNat cols),
471− I.FromLists e (I.FromNat cols) (),
472− I.FromLists e (I.FromNat cols) (I.FromNat cols),
473− Bounded a,
474− Enum a,
475− Num e,
476− Ord e
477− )
478− =>
479− (a -> Bool) -> Matrix e cols rows -> Matrix e cols rows -> Matrix e cols rows
480−cond p (M a) (M b) = M (I.cond p a b)
481−
482−-- Pretty print
483−
484−pretty :: (KnownNat (I.Count (I.FromNat cols)), Show e) => Matrix e cols rows -> String
485−pretty (M m) = I.pretty m
486−
487−prettyPrint :: (KnownNat (I.Count (I.FromNat cols)), Show e) => Matrix e cols rows -> IO ()
488−prettyPrint (M m) = I.prettyPrint m
src/Matrix/Type.hsdeleted−591
@@ -1,591 +0,0 @@
1−{-# LANGUAGE AllowAmbiguousTypes #-}
2−{-# LANGUAGE DataKinds #-}
3−{-# LANGUAGE DerivingVia #-}
4−{-# LANGUAGE FlexibleContexts #-}
5−{-# LANGUAGE FlexibleInstances #-}
6−{-# LANGUAGE GADTs #-}
7−{-# LANGUAGE KindSignatures #-}
8−{-# LANGUAGE MultiParamTypeClasses #-}
9−{-# LANGUAGE NoStarIsType #-}
10−{-# LANGUAGE RankNTypes #-}
11−{-# LANGUAGE ScopedTypeVariables #-}
12−{-# LANGUAGE TypeApplications #-}
13−{-# LANGUAGE TypeOperators #-}
14−{-# LANGUAGE UndecidableInstances #-}
15−
16−-----------------------------------------------------------------------------
17−-- |
18−-- Module : Matrix.Type
19−-- Copyright : (c) Armando Santos 2019-2020
20−-- Maintainer : armandoifsantos@gmail.com
21−-- Stability : experimental
22−--
23−-- The LAoP discipline generalises relations and functions treating them as
24−-- Boolean matrices and in turn consider these as arrows.
25−--
26−-- __LAoP__ is a library for algebraic (inductive) construction and manipulation of matrices
27−-- in Haskell. See <https://github.com/bolt12/master-thesis my Msc Thesis> for the
28−-- motivation behind the library, the underlying theory, and implementation details.
29−--
30−-- This module offers a newtype wrapper around 'Matrix.Type.Matrix' that
31−-- uses arbitrary types instead of canonical data types for the matrices
32−-- dimensions.
33−--
34−-- __NOTE__: If the types in the dimensions are custom they must need to
35−-- implement a 'Generic' instance.
36−--
37−-----------------------------------------------------------------------------
38−
39−module Matrix.Type
40− ( -- | LAoP (Linear Algebra of Programming) Inductive Matrix definition.
41− --
42− -- LAoP generalises relations and functions treating them as
43− -- Boolean matrices and in turn consider these as arrows.
44− -- This library offers many of the combinators mentioned in the work of
45− -- Macedo (2012) and Oliveira (2012).
46− --
47− -- This definition is a wrapper around 'Matrix.Type' but
48− -- dimensions are arbitrary data types. Type inference might not
49− -- be as desired.
50−
51− -- __NOTE__: If the types in the dimensions are custom they must need to
52− -- implement a 'Generic' instance.
53− --
54−
55− -- * Type safe matrix representation
56− Matrix (..),
57−
58− -- * Type aliases
59− Zero,
60− One,
61−
62− -- * Primitives
63− empty,
64− one,
65− junc,
66− split,
67−
68− -- * Auxiliary type families
69− I.FromNat,
70− I.Count,
71− I.Normalize,
72−
73− -- * Matrix construction and conversion
74− I.FromLists,
75− fromLists,
76− toLists,
77− toList,
78− matrixBuilder,
79− row,
80− col,
81− zeros,
82− ones,
83− bang,
84− constant,
85−
86− -- * Misc
87− -- ** Get dimensions
88− columns,
89− rows,
90−
91− -- ** Matrix Transposition
92− tr,
93−
94− -- ** Selective operator
95− select,
96−
97− -- ** McCarthy's Conditional
98− cond,
99−
100− -- ** Matrix "abiding"
101− abideJS,
102− abideSJ,
103−
104− -- * Biproduct approach
105− -- ** Split
106− (===),
107− -- *** Projections
108− p1,
109− p2,
110− -- ** Junc
111− (|||),
112− -- *** Injections
113− i1,
114− i2,
115− -- ** Bifunctors
116− (-|-),
117− (><),
118−
119− -- ** Applicative matrix combinators
120−
121− -- | Note that given the restrictions imposed it is not possible to
122− -- implement the standard type classes present in standard Haskell.
123− -- *** Matrix pairing projections
124− kp1,
125− kp2,
126−
127− -- *** Matrix pairing
128− khatri,
129−
130− -- * Matrix composition and lifting
131−
132− -- ** Arrow matrix combinators
133−
134− -- | Note that given the restrictions imposed it is not possible to
135− -- implement the standard type classes present in standard Haskell.
136− identity,
137− comp,
138− fromF,
139− fromF',
140−
141− -- * Matrix printing
142− pretty,
143− prettyPrint
144− )
145−where
146−
147−import Data.Void
148−import Data.Proxy
149−import Data.Kind
150−import GHC.TypeLits
151−import Control.DeepSeq
152−import qualified Control.Category as C
153−import qualified Matrix.Internal as I
154−
155−newtype Matrix e (cols :: Type) (rows :: Type) = M (I.Matrix e (I.Normalize cols) (I.Normalize rows))
156− deriving (Show, Num, Eq, NFData) via (I.Matrix e (I.Normalize cols) (I.Normalize rows))
157−
158−-- | It isn't possible to implement the 'id' function so it's
159−-- implementation is 'undefined'. However 'comp' can be and this partial
160−-- class implementation exists just to make the code more readable.
161−--
162−-- Please use 'identity' instead.
163−instance (Num e) => C.Category (Matrix e) where
164− id = undefined
165− (.) = comp
166−
167−-- | Zero type alias
168−type Zero = Void
169−
170−-- | One type alias
171−type One = ()
172−
173−-- Primitives
174−
175−-- | Empty matrix constructor
176−empty :: Matrix e Zero Zero
177−empty = M I.Empty
178−
179−-- | Unit matrix constructor
180−one :: e -> Matrix e One One
181−one = M . I.One
182−
183−-- | Matrix 'Junc' constructor
184−junc ::
185− (I.Normalize (Either a b) ~ Either (I.Normalize a) (I.Normalize b)) =>
186− Matrix e a rows ->
187− Matrix e b rows ->
188− Matrix e (Either a b) rows
189−junc (M a) (M b) = M (I.Junc a b)
190−
191−infixl 3 |||
192−-- | Matrix 'Junc' constructor
193−(|||) ::
194− (I.Normalize (Either a b) ~ Either (I.Normalize a) (I.Normalize b)) =>
195− Matrix e a rows ->
196− Matrix e b rows ->
197− Matrix e (Either a b) rows
198−(|||) = junc
199−
200−-- | Matrix 'Split' constructor
201−split ::
202− (I.Normalize (Either a b) ~ Either (I.Normalize a) (I.Normalize b)) =>
203− Matrix e cols a ->
204− Matrix e cols b ->
205− Matrix e cols (Either a b)
206−split (M a) (M b) = M (I.Split a b)
207−
208−infixl 2 ===
209−-- | Matrix 'Split' constructor
210−(===) ::
211− (I.Normalize (Either a b) ~ Either (I.Normalize a) (I.Normalize b)) =>
212− Matrix e cols a ->
213− Matrix e cols b ->
214− Matrix e cols (Either a b)
215−(===) = split
216−
217−-- Construction
218−
219−-- | Build a matrix out of a list of list of elements. Throws a runtime
220−-- error if the dimensions do not match.
221−fromLists :: (I.FromLists e (I.Normalize cols) (I.Normalize rows)) => [[e]] -> Matrix e cols rows
222−fromLists = M . I.fromLists
223−
224−-- | Matrix builder function. Constructs a matrix provided with
225−-- a construction function.
226−matrixBuilder ::
227− (I.FromLists e (I.Normalize cols) (I.Normalize rows), KnownNat (I.Count (I.Normalize cols)), KnownNat (I.Count (I.Normalize rows))) =>
228− ((Int, Int) -> e) ->
229− Matrix e cols rows
230−matrixBuilder = M . I.matrixBuilder
231−
232−-- | Constructs a column vector matrix
233−col :: (I.FromLists e () (I.Normalize rows)) => [e] -> Matrix e One rows
234−col = M . I.col
235−
236−-- | Constructs a row vector matrix
237−row :: (I.FromLists e (I.Normalize cols) ()) => [e] -> Matrix e cols One
238−row = M . I.row
239−
240−-- | Lifts functions to matrices with arbitrary dimensions.
241−--
242−-- NOTE: Be careful to not ask for a matrix bigger than the cardinality of
243−-- types @a@ or @b@ allows.
244−fromF ::
245− ( Bounded a,
246− Bounded b,
247− Enum a,
248− Enum b,
249− Eq b,
250− Num e,
251− Ord e,
252− KnownNat (I.Count (I.Normalize cols)),
253− KnownNat (I.Count (I.Normalize rows)),
254− I.FromLists e (I.Normalize rows) (I.Normalize cols)
255− ) =>
256− (a -> b) ->
257− Matrix e cols rows
258−fromF = M . I.fromF
259−
260−-- | Lifts functions to matrices with dimensions matching @a@ and @b@
261−-- cardinality's.
262−fromF' ::
263− ( Bounded a,
264− Bounded b,
265− Enum a,
266− Enum b,
267− Eq b,
268− Num e,
269− Ord e,
270− KnownNat (I.Count (I.Normalize a)),
271− KnownNat (I.Count (I.Normalize b)),
272− I.FromLists e (I.Normalize b) (I.Normalize a)
273− ) =>
274− (a -> b) ->
275− Matrix e a b
276−fromF' = M . I.fromF'
277−
278−-- Conversion
279−
280−-- | Converts a matrix to a list of lists of elements.
281−toLists :: Matrix e cols rows -> [[e]]
282−toLists (M m) = I.toLists m
283−
284−-- | Converts a matrix to a list of elements.
285−toList :: Matrix e cols rows -> [e]
286−toList (M m) = I.toList m
287−
288−-- Zeros Matrix
289−
290−-- | The zero matrix. A matrix wholly filled with zeros.
291−zeros ::
292− (Num e, I.FromLists e (I.Normalize cols) (I.Normalize rows), KnownNat (I.Count (I.Normalize cols)), KnownNat (I.Count (I.Normalize rows))) =>
293− Matrix e cols rows
294−zeros = M I.zeros
295−
296−-- Ones Matrix
297−
298−-- | The ones matrix. A matrix wholly filled with ones.
299−--
300−-- Also known as T (Top) matrix.
301−ones ::
302− (Num e, I.FromLists e (I.Normalize cols) (I.Normalize rows), KnownNat (I.Count (I.Normalize cols)), KnownNat (I.Count (I.Normalize rows))) =>
303− Matrix e cols rows
304−ones = M I.ones
305−
306−-- Const Matrix
307−
308−-- | The constant matrix constructor. A matrix wholly filled with a given
309−-- value.
310−constant ::
311− (Num e, I.FromLists e (I.Normalize cols) (I.Normalize rows), KnownNat (I.Count (I.Normalize cols)), KnownNat (I.Count (I.Normalize rows))) =>
312− e ->
313− Matrix e cols rows
314−constant = M . I.constant
315−
316−-- Bang Matrix
317−
318−-- | The T (Top) row vector matrix.
319−bang ::
320− forall e cols.
321− (Num e, Enum e, I.FromLists e (I.Normalize cols) (), KnownNat (I.Count (I.Normalize cols))) =>
322− Matrix e cols One
323−bang = M I.bang
324−
325−-- Identity Matrix
326−
327−-- | Identity matrix
328−identity ::
329− (Num e, I.FromLists e (I.Normalize a) (I.Normalize a), KnownNat (I.Count (I.Normalize a))) =>
330− Matrix e a a
331−identity = M I.identity
332−
333−-- Matrix composition (MMM)
334−
335−-- | Matrix composition. Equivalent to matrix-matrix multiplication.
336−--
337−-- This definition takes advantage of divide-and-conquer and fusion laws
338−-- from LAoP.
339−comp :: (Num e) => Matrix e cr rows -> Matrix e cols cr -> Matrix e cols rows
340−comp (M a) (M b) = M (I.comp a b)
341−
342−-- | Biproduct first component projection
343−p1 ::
344− ( Num e,
345− KnownNat (I.Count (I.Normalize n)),
346− KnownNat (I.Count (I.Normalize m)),
347− I.FromLists e (I.Normalize n) (I.Normalize m),
348− I.FromLists e (I.Normalize m) (I.Normalize m),
349− I.Normalize (Either m n) ~ Either (I.Normalize m) (I.Normalize n)
350− ) =>
351− Matrix e (Either m n) m
352−p1 = M I.p1
353−
354−-- | Biproduct second component projection
355−p2 ::
356− ( Num e,
357− KnownNat (I.Count (I.Normalize n)),
358− KnownNat (I.Count (I.Normalize m)),
359− I.FromLists e (I.Normalize m) (I.Normalize n),
360− I.FromLists e (I.Normalize n) (I.Normalize n),
361− I.Normalize (Either m n) ~ Either (I.Normalize m) (I.Normalize n)
362− ) =>
363− Matrix e (Either m n) n
364−p2 = M I.p2
365−
366−-- Injections
367−
368−-- | Biproduct first component injection
369−i1 ::
370− ( Num e,
371− KnownNat (I.Count (I.Normalize n)),
372− KnownNat (I.Count (I.Normalize m)),
373− I.FromLists e (I.Normalize n) (I.Normalize m),
374− I.FromLists e (I.Normalize m) (I.Normalize m),
375− I.Normalize (Either m n) ~ Either (I.Normalize m) (I.Normalize n)
376− ) =>
377− Matrix e m (Either m n)
378−i1 = tr p1
379−
380−-- | Biproduct second component injection
381−i2 ::
382− ( Num e,
383− KnownNat (I.Count (I.Normalize n)),
384− KnownNat (I.Count (I.Normalize m)),
385− I.FromLists e (I.Normalize m) (I.Normalize n),
386− I.FromLists e (I.Normalize n) (I.Normalize n),
387− I.Normalize (Either m n) ~ Either (I.Normalize m) (I.Normalize n)
388− ) =>
389− Matrix e n (Either m n)
390−i2 = tr p2
391−
392−-- Dimensions
393−
394−-- | Obtain the number of rows.
395−--
396−-- NOTE: The 'KnownNat' constaint is needed in order to obtain the
397−-- dimensions in constant time.
398−--
399−-- TODO: A 'rows' function that does not need the 'KnownNat' constraint in
400−-- exchange for performance.
401−rows :: (KnownNat (I.Count (I.Normalize rows))) => Matrix e cols rows -> Int
402−rows (M m) = I.rows m
403−
404−-- | Obtain the number of columns.
405−--
406−-- NOTE: The 'KnownNat' constaint is needed in order to obtain the
407−-- dimensions in constant time.
408−--
409−-- TODO: A 'columns' function that does not need the 'KnownNat' constraint in
410−-- exchange for performance.
411−columns :: (KnownNat (I.Count (I.Normalize cols))) => Matrix e cols rows -> Int
412−columns (M m) = I.columns m
413−
414−-- Coproduct Bifunctor
415−
416−infixl 5 -|-
417−
418−-- | Matrix coproduct functor also known as matrix direct sum.
419−(-|-) ::
420− ( Num e,
421− KnownNat (I.Count (I.Normalize j)),
422− KnownNat (I.Count (I.Normalize k)),
423− I.FromLists e (I.Normalize k) (I.Normalize k),
424− I.FromLists e (I.Normalize j) (I.Normalize k),
425− I.FromLists e (I.Normalize k) (I.Normalize j),
426− I.FromLists e (I.Normalize j) (I.Normalize j),
427− I.Normalize (Either n m) ~ Either (I.Normalize n) (I.Normalize m),
428− I.Normalize (Either k j) ~ Either (I.Normalize k) (I.Normalize j)
429− ) =>
430− Matrix e n k ->
431− Matrix e m j ->
432− Matrix e (Either n m) (Either k j)
433−(-|-) (M a) (M b) = M ((I.-|-) a b)
434−
435−-- Khatri Rao Product and projections
436−
437−-- | Khatri Rao product first component projection matrix.
438−kp1 ::
439− forall e m k .
440− ( Num e,
441− KnownNat (I.Count (I.Normalize m)),
442− KnownNat (I.Count (I.Normalize k)),
443− KnownNat (I.Count (I.Normalize (m, k))),
444− I.FromLists e (I.Normalize (m, k)) (I.Normalize m),
445− I.Normalize (m, k) ~ I.Normalize (I.Normalize m, I.Normalize k)
446− ) => Matrix e (m, k) m
447−kp1 = M (I.kp1 @e @(I.Normalize m) @(I.Normalize k))
448−
449−-- | Khatri Rao product second component projection matrix.
450−kp2 ::
451− forall e m k.
452− ( Num e,
453− KnownNat (I.Count (I.Normalize k)),
454− KnownNat (I.Count (I.Normalize m)),
455− KnownNat (I.Count (I.Normalize (m, k))),
456− I.FromLists e (I.Normalize (m, k)) (I.Normalize k),
457− I.Normalize (m, k) ~ I.Normalize (I.Normalize m, I.Normalize k)
458− ) => Matrix e (m, k) k
459−kp2 = M (I.kp2 @e @(I.Normalize m) @(I.Normalize k))
460−
461−-- | Khatri Rao Matrix product also known as matrix pairing.
462−--
463−-- NOTE: That this is not a true categorical product, see for instance:
464−--
465−-- @
466−-- | kp1 `comp` khatri a b == a
467−-- khatri a b ==> |
468−-- | kp2 `comp` khatri a b == b
469−-- @
470−--
471−-- __Emphasis__ on the implication symbol.
472−khatri ::
473− forall e cols a b.
474− ( Num e,
475− KnownNat (I.Count (I.Normalize a)),
476− KnownNat (I.Count (I.Normalize b)),
477− KnownNat (I.Count (I.Normalize (a, b))),
478− I.FromLists e (I.Normalize (a, b)) (I.Normalize a),
479− I.FromLists e (I.Normalize (a, b)) (I.Normalize b),
480− I.Normalize (a, b) ~ I.Normalize (I.Normalize a, I.Normalize b)
481− ) => Matrix e cols a -> Matrix e cols b -> Matrix e cols (a, b)
482−khatri a b =
483− let kp1' = kp1 @e @a @b
484− kp2' = kp2 @e @a @b
485− in comp (tr kp1') a * comp (tr kp2') b
486−
487−-- Product Bifunctor (Kronecker)
488−
489−infixl 4 ><
490−
491−-- | Matrix product functor also known as kronecker product
492−(><) ::
493− forall e m p n q.
494− ( Num e,
495− KnownNat (I.Count (I.Normalize m)),
496− KnownNat (I.Count (I.Normalize n)),
497− KnownNat (I.Count (I.Normalize p)),
498− KnownNat (I.Count (I.Normalize q)),
499− KnownNat (I.Count (I.Normalize (m, n))),
500− KnownNat (I.Count (I.Normalize (p, q))),
501− I.FromLists e (I.Normalize (m, n)) (I.Normalize m),
502− I.FromLists e (I.Normalize (m, n)) (I.Normalize n),
503− I.FromLists e (I.Normalize (p, q)) (I.Normalize p),
504− I.FromLists e (I.Normalize (p, q)) (I.Normalize q),
505− I.Normalize (m, n) ~ I.Normalize (I.Normalize m, I.Normalize n),
506− I.Normalize (p, q) ~ I.Normalize (I.Normalize p, I.Normalize q)
507− ) => Matrix e m p -> Matrix e n q -> Matrix e (m, n) (p, q)
508−(><) a b =
509− let kp1' = kp1 @e @m @n
510− kp2' = kp2 @e @m @n
511− in khatri (comp a kp1') (comp b kp2')
512−
513−-- Matrix abide Junc Split
514−
515−-- | Matrix "abiding" followin the 'Junc'-'Split' abide law.
516−--
517−-- Law:
518−--
519−-- @
520−-- 'Junc' ('Split' a c) ('Split' b d) == 'Split' ('Junc' a b) ('Junc' c d)
521−-- @
522−abideJS :: Matrix e cols rows -> Matrix e cols rows
523−abideJS (M m) = M (I.abideJS m)
524−
525−-- Matrix abide Split Junc
526−
527−-- | Matrix "abiding" followin the 'Split'-'Junc' abide law.
528−--
529−-- Law:
530−--
531−-- @
532−-- 'Split' ('Junc' a b) ('Junc' c d) == 'Junc' ('Split' a c) ('Split' b d)
533−-- @
534−abideSJ :: Matrix e cols rows -> Matrix e cols rows
535−abideSJ (M m) = M (I.abideSJ m)
536−
537−-- Matrix transposition
538−
539−-- | Matrix transposition.
540−tr :: Matrix e cols rows -> Matrix e rows cols
541−tr (M m) = M (I.tr m)
542−
543−-- Selective 'select' operator
544−
545−-- | Selective functors 'select' operator equivalent inspired by the
546−-- ArrowMonad solution presented in the paper.
547−select ::
548− ( Bounded a,
549− Bounded b,
550− Enum a,
551− Eq b,
552− Enum b,
553− Num e,
554− Ord e,
555− KnownNat (I.Count (I.Normalize a)),
556− KnownNat (I.Count (I.Normalize b)),
557− KnownNat (I.Count (I.Normalize cols)),
558− I.FromLists e (I.Normalize b) (I.Normalize a),
559− I.FromLists e (I.Normalize b) (I.Normalize b),
560− I.Normalize (Either a b) ~ Either (I.Normalize a) (I.Normalize b)
561− )
562− => Matrix e cols (Either a b) -> (a -> b) -> Matrix e cols b
563−select (M m) y = M (I.select m y)
564−
565−-- McCarthy's Conditional
566−
567−-- | McCarthy's Conditional expresses probabilistic choice.
568−cond ::
569− ( I.Normalize (I.Normalize a) ~ I.Normalize a,
570− KnownNat (I.Count (I.Normalize a)),
571− I.FromLists e () (I.Normalize a),
572− I.FromLists e (I.Normalize a) (),
573− I.FromLists e (I.Normalize a) (I.Normalize a),
574− Bounded a,
575− Enum a,
576− Num e,
577− Ord e
578− )
579− =>
580− (a -> Bool) -> Matrix e a b -> Matrix e a b -> Matrix e a b
581−cond p (M a) (M b) = M (I.cond p a b)
582−
583−-- Pretty print
584−
585−-- | Matrix pretty printer
586−pretty :: (KnownNat (I.Count (I.Normalize cols)), Show e) => Matrix e cols rows -> String
587−pretty (M m) = I.pretty m
588−
589−-- | Matrix pretty printer
590−prettyPrint :: (KnownNat (I.Count (I.Normalize cols)), Show e) => Matrix e cols rows -> IO ()
591−prettyPrint (M m) = I.prettyPrint m
src/Utils/Internal.hsdeleted−158
@@ -1,158 +0,0 @@
1−{-# LANGUAGE DataKinds #-}
2−{-# LANGUAGE FlexibleInstances #-}
3−{-# LANGUAGE GeneralizedNewtypeDeriving #-}
4−{-# LANGUAGE KindSignatures #-}
5−{-# LANGUAGE ScopedTypeVariables #-}
6−
7−module Utils.Internal
8− ( -- | This is an internal module and it is not meant to be imported.
9− --
10− -- Utility module that provides the 'Natural' data type.
11− -- The semantic associated with this data type is that
12− -- it's meant to be a restricted 'Int' value. For example
13− -- the type @Natural 6@ can only be instanciated with @Nat n@
14− -- where @0 <= n <= 6@. Why, You might ask, because with normal
15− -- 'Int's it is not possible to have a decent @Enum (Int, Int)@
16− -- instance. See the following probabilistic programming model as and
17− -- example:
18− --
19− -- We want to calculate the probability of the sum of two dice throws.
20− -- To do this we start by defining the sample space:
21− --
22− -- @
23− -- type SampleSpace = Int -- We think 'Int' are enough
24− --
25− -- die :: Dist Int 6
26− -- die = unifrom [1..6]
27− --
28− -- -- Promote 'Int' addition to a matrix
29− -- addM = fromF (uncurry (+)) -- Impossible
30− -- @
31− --
32− -- The last line is impossible because @(Int, Int)@ does not have
33− -- a good 'Enum' instance: @[(0, 1), (0, 2), .. (0, maxBound), (1, 0),
34− -- ..]@. And we'd like the addition matrix to be of 36 columns by 12
35− -- rows but limited to integers up to @6@!
36− --
37− -- One way to solve this issue is by defining and auxilary data type to
38− -- represent the sample space:
39− --
40− -- @
41− -- data SampleSpace = S1 | S2 | S3 | S4 | S5 | S6
42− -- deriving (Show, Eq, Enum, Bounded) -- Enum and Bounded are
43− -- important
44− -- @
45− --
46− -- And write the sample space addition function:
47− --
48− -- @
49− -- ssAdd :: SampleSpace -> SampleSpace -> Int
50− -- ssAdd a b = (fromEnum a + 1) + (fromEnum b + 1)
51− -- @
52− --
53− -- And then promote that function to matrix and everything is alright:
54− --
55− -- @
56− -- ssAddM = fromF' (uncurry ssAdd)
57− --
58− -- dieSumProb = ssAddM `comp` (khatri die die)
59− -- @
60− --
61− -- This is a nice solution for small sample spaces. But for larger ones
62− -- it is not feasible to write a data type with hundreds of constructors
63− -- and then write manipulation functions that need to deal with them.
64− -- To mitigate this limitation the 'Natural' type comes a long way and
65− -- allows one to model the sample in an easier way. See for instance:
66− --
67− -- @
68− -- ssAdd :: Natural 6 -> Natural 6 -> Natural 12
69− -- ssAdd = coerceNat (+)
70− --
71− -- ssAddM = fromF' (uncurry sumSS)
72− --
73− -- die :: Dist (Natural 6) 6
74− -- die = uniform [nat @6 1 .. nat 6]
75− --
76− -- dieSumProb = ssAddM `comp` (khatri die die)
77− -- @
78− --
79− -- * 'Natural' data type
80− Natural,
81− nat,
82−
83− -- * Coerce auxiliar functions to help promote 'Int' typed functions to
84− -- 'Natural' typed functions.
85− coerceNat,
86− coerceNat2,
87− )
88−where
89−
90−import Data.Coerce
91−import Data.Proxy
92−import GHC.TypeLits
93−
94−-- | Wrapper around 'Int's that have a restrictive semantic associated.
95−-- A value of type @'Natural' n m@ can only be instanciated with some 'Int'
96−-- @i@ that's @n <= i <= m@.
97−newtype Natural (start :: Nat) (end :: Nat) = Nat Int
98− deriving (Show, Read, Eq, Num)
99−
100−-- | Natural constructor function. Throws a runtime error if the 'Int'
101−-- value is greater than the corresponding @m@ or lower than @n@ in the @'Natural' n m@ type.
102−nat :: forall n m . (KnownNat n, KnownNat m) => Int -> Natural n m
103−nat i =
104− let start = fromInteger (natVal (Proxy :: Proxy n))
105− end = fromInteger (natVal (Proxy :: Proxy m))
106− in if start <= i && i <= end
107− then Nat i
108− else error "Off limits"
109−
110−-- | Auxiliary function that promotes binary 'Int' functions to 'Natural'
111−-- binary functions.
112−coerceNat :: (Int -> Int -> Int) -> (Natural a a' -> Natural b b' -> Natural c c')
113−coerceNat = coerce
114−
115−-- | Auxiliary function that promotes ternary (binary) 'Int' functions to 'Natural'
116−-- functions.
117−coerceNat2 :: ((Int, Int) -> Int -> Int) -> ((Natural a a', Natural b b') -> Natural c c' -> Natural d d')
118−coerceNat2 = coerce
119−
120−instance (KnownNat n, KnownNat m) => Bounded (Natural n m) where
121− minBound = Nat $ fromInteger (natVal (Proxy :: Proxy n))
122− maxBound = Nat $ fromInteger (natVal (Proxy :: Proxy m))
123−
124−instance (KnownNat n, KnownNat m) => Enum (Natural n m) where
125− toEnum i =
126− let start = fromInteger (natVal (Proxy :: Proxy n))
127− in nat (start + i)
128− -- | Throws a runtime error if the value is off limits
129− fromEnum (Nat nat) =
130− let start = fromInteger (natVal (Proxy :: Proxy n))
131− end = fromInteger (natVal (Proxy :: Proxy m))
132− in if start <= nat && nat <= end
133− then nat - start
134− else error "Off limits"
135−
136−-- | Optimized 'Enum' instance for tuples that comply with the given
137−-- constraints.
138−instance
139− ( Enum a,
140− Enum b,
141− Bounded b
142− ) =>
143− Enum (a, b)
144− where
145−
146− toEnum i =
147− let (listB :: [b]) = [minBound .. maxBound]
148− lengthB = length listB
149− fstI = div i lengthB
150− sndI = mod i lengthB
151− in (toEnum fstI, toEnum sndI)
152−
153− fromEnum (a, b) =
154− let (listB :: [b]) = [minBound .. maxBound]
155− lengthB = length listB
156− fstI = fromEnum a
157− sndI = fromEnum b
158− in fstI * lengthB + sndI
stack-8.8.3.yamlnew file+1
@@ -0,0 +1 @@
1+resolver: lts-15.5
stack.yaml+1−66
@@ -1,66 +1 @@
1−# This file was automatically generated by 'stack init'
2−#
3−# Some commonly used options have been documented as comments in this file.
4−# For advanced use and comprehensive documentation of the format, please see:
5−# https://docs.haskellstack.org/en/stable/yaml_configuration/
6−
7−# Resolver to choose a 'specific' stackage snapshot or a compiler version.
8−# A snapshot resolver dictates the compiler version and the set of packages
9−# to be used for project dependencies. For example:
10−#
11−# resolver: lts-3.5
12−# resolver: nightly-2015-09-21
13−# resolver: ghc-7.10.2
14−#
15−# The location of a snapshot can be provided as a file or url. Stack assumes
16−# a snapshot provided as a file might change, whereas a url resource does not.
17−#
18−# resolver: ./custom-snapshot.yaml
19−# resolver: https://example.com/snapshots/2018-01-01.yaml
20−resolver: lts-14.18
21−
22−# User packages to be built.
23−# Various formats can be used as shown in the example below.
24−#
25−# packages:
26−# - some-directory
27−# - https://example.com/foo/bar/baz-0.0.2.tar.gz
28−# subdirs:
29−# - auto-update
30−# - wai
31−packages:
32−- .
33−# Dependency packages to be pulled from upstream that are not in the resolver.
34−# These entries can reference officially published versions as well as
35−# forks / in-progress versions pinned to a git hash. For example:
36−#
37−# extra-deps:
38−# - acme-missiles-0.3
39−# - git: https://github.com/commercialhaskell/stack.git
40−# commit: e7b331f14bcffb8367cd58fbfc8b40ec7642100a
41−#
42−# extra-deps: []
43−
44−# Override default flag values for local packages and extra-deps
45−# flags: {}
46−
47−# Extra package databases containing global packages
48−# extra-package-dbs: []
49−
50−# Control whether we use the GHC we find on the path
51−# system-ghc: true
52−#
53−# Require a specific version of stack, using version ranges
54−# require-stack-version: -any # Default
55−# require-stack-version: ">=2.1"
56−#
57−# Override the architecture used by stack, especially useful on Windows
58−# arch: i386
59−# arch: x86_64
60−#
61−# Extra directories used by stack for building
62−# extra-include-dirs: [/path/to/dir]
63−# extra-lib-dirs: [/path/to/dir]
64−#
65−# Allow a newer minor version of GHC than the snapshot specifies
66−# compiler-check: newer-minor
1+resolver: lts-14.3
stack.yaml.lock+4−4
@@ -6,7 +6,7 @@
66packages: []
77snapshots:
88- completed:
9− size: 524789
10− url: https://raw.githubusercontent.com/commercialhaskell/stackage-snapshots/master/lts/14/18.yaml
11− sha256: 646be71223e08234131c6989912e6011e01b9767bc447b6d466a35e14360bdf2
12− original: lts-14.18
9+ size: 523878
10+ url: https://raw.githubusercontent.com/commercialhaskell/stackage-snapshots/master/lts/14/3.yaml
11+ sha256: 470c46c27746a48c7c50f829efc0cf00112787a7804ee4ac7a27754658f6d92c
12+ original: lts-14.3
test/Examples/Quantum.hsnew file+31
@@ -0,0 +1,31 @@
1+{-# LANGUAGE StandaloneDeriving #-}
2+module Examples.Quantum where
3+
4+import LAoP.Utils
5+import LAoP.Matrix.Type
6+import Data.Complex
7+import Prelude hiding (id, (.))
8+
9+deriving instance Ord a => Ord (Complex a)
10+
11+xor :: (Bool, Bool) -> Bool
12+xor (False, b) = b
13+xor (True, b) = not b
14+
15+ker :: Num e => Matrix e a b -> Matrix e a a
16+ker m = tr m . m
17+
18+cnot :: Matrix (Complex Double) (Bool, Bool) (Bool, Bool)
19+cnot = kr fstM (fromF xor)
20+
21+ccnot :: (Num e, Ord e) => Matrix e ((Bool, Bool), Bool) ((Bool, Bool), Bool)
22+ccnot = kr fstM (fromF f)
23+ where
24+ f = xor . tp (uncurry (&&)) id
25+ tp f g (a,b) = (f a, g b)
26+
27+had :: Matrix (Complex Double) Bool Bool
28+had = (1/sqrt 2) .| fromLists [[1, 1], [1, -1]]
29+
30+bell :: Matrix (Complex Double) (Bool, Bool) (Bool, Bool)
31+bell = cnot . (had >< iden)
test/Examples/Readme.hsnew file+184
@@ -0,0 +1,184 @@
1+{-# LANGUAGE GADTs #-}
2+{-# LANGUAGE DeriveGeneric #-}
3+{-# LANGUAGE FlexibleContexts #-}
4+{-# LANGUAGE TypeApplications #-}
5+{-# LANGUAGE DataKinds #-}
6+
7+module Examples.Readme
8+ ( exec
9+ )
10+ where
11+
12+import LAoP.Matrix.Type
13+import qualified LAoP.Relation as R
14+import LAoP.Utils
15+import LAoP.Dist
16+import GHC.TypeLits
17+import Data.Coerce
18+import qualified GHC.Generics as G
19+import Prelude hiding (id, (.))
20+
21+-- Monty Hall Problem
22+data Outcome = Win | Lose
23+ deriving (Bounded, Enum, Eq, Show, G.Generic)
24+
25+switch :: Outcome -> Outcome
26+switch Win = Lose
27+switch Lose = Win
28+
29+firstChoice :: Matrix Double () Outcome
30+firstChoice = col [1/3, 2/3]
31+
32+secondChoice :: Matrix Double Outcome Outcome
33+secondChoice = fromF switch
34+
35+-- Dice sum
36+
37+type SS = Natural 1 6 -- Sample Space
38+
39+sumSS :: SS -> SS -> Natural 2 12
40+sumSS = coerceNat (+)
41+
42+sumSSM = fromF (uncurry sumSS)
43+
44+condition :: (Int, Int) -> Int -> Int
45+condition (fst, snd) thrd = if fst == snd
46+ then fst * 3
47+ else fst + snd + thrd
48+
49+conditionSS :: (SS, SS) -> SS -> Natural 3 18
50+conditionSS = coerceNat2 condition
51+
52+conditionalThrows = fromF (uncurry conditionSS) . kr (kr die die) die
53+
54+die :: Matrix Double () SS
55+die = col $ map (const (1/6)) [nat @1 @6 1 .. nat 6]
56+
57+-- Sprinkler
58+data G = Dry | Wet
59+ deriving (Bounded, Enum, Eq, Show, G.Generic)
60+
61+data S = Off | On
62+ deriving (Bounded, Enum, Eq, Show, G.Generic)
63+
64+data R = No | Yes
65+ deriving (Bounded, Enum, Eq, Show, G.Generic)
66+
67+rain :: Matrix Double () R
68+rain = matrixBuilder gen
69+ where
70+ gen (_, No) = 0.8
71+ gen (_, Yes) = 0.2
72+
73+sprinkler :: Matrix Double R S
74+sprinkler = matrixBuilder gen
75+ where
76+ gen (No, Off) = 0.6
77+ gen (No, On) = 0.4
78+ gen (Yes, Off) = 0.99
79+ gen (Yes, On) = 0.01
80+
81+grass :: Matrix Double (S, R) G
82+grass = matrixBuilder gen
83+ where
84+ gen ((Off, No), Dry) = 1
85+ gen ((Off, Yes), Dry) = 0.2
86+ gen ((On, No), Dry) = 0.1
87+ gen ((On, Yes), Dry) = 0.01
88+ gen ((Off, No), Wet) = 0
89+ gen ((Off, Yes), Wet) = 0.8
90+ gen ((On, No), Wet) = 0.9
91+ gen ((On, Yes), Wet) = 0.99
92+
93+tag f = kr f id
94+
95+state g s r = tag g . tag s . r
96+
97+grass_wet :: Matrix Double () (G, (S, R)) -> Matrix Double One One
98+grass_wet state = row [0,1] . fstM . state
99+
100+rainning :: Matrix Double (G, (S, R)) One
101+rainning = row [0,1] . sndM . sndM
102+
103+-- Alcuin Puzzle
104+
105+data Being = Farmer | Fox | Goose | Beans
106+ deriving (Bounded, Enum, Eq, Show, G.Generic)
107+
108+data Bank = LeftB | RightB
109+ deriving (Bounded, Enum, Eq, Show, G.Generic)
110+
111+eats :: Being -> Being -> Bool
112+eats Fox Goose = True
113+eats Goose Beans = True
114+eats _ _ = False
115+
116+eatsR :: R.Relation Being Being
117+eatsR = R.toRel eats
118+
119+cross :: Bank -> Bank
120+cross LeftB = RightB
121+cross RightB = LeftB
122+
123+crossR :: R.Relation Bank Bank
124+crossR = R.fromF cross
125+
126+-- | Initial state, everyone in the left bank
127+locationLeft :: Being -> Bank
128+locationLeft _ = LeftB
129+
130+locationLeftR :: R.Relation Being Bank
131+locationLeftR = R.fromF locationLeft
132+
133+-- | Initial state, everyone in the right bank
134+locationRight :: Being -> Bank
135+locationRight _ = RightB
136+
137+locationRightR :: R.Relation Being Bank
138+locationRightR = R.fromF locationRight
139+
140+-- Properties
141+
142+-- Being at the same bank
143+sameBank :: R.Relation Being Bank -> R.Relation Being Being
144+sameBank = R.ker
145+
146+-- Risk of somebody eating somebody else
147+canEat :: R.Relation Being Bank -> R.Relation Being Being
148+canEat w = sameBank w `R.intersection` eatsR
149+
150+-- "Starvation" property.
151+inv :: R.Relation Being Bank -> Bool
152+inv w = (w `R.comp` canEat w) `R.sse` (w `R.comp` farmer)
153+ where
154+ farmer :: R.Relation Being Being
155+ farmer = R.fromF (const Farmer)
156+
157+-- Arbitrary state
158+bankState :: Being -> Bank -> Bool
159+bankState Farmer LeftB = True
160+bankState Fox LeftB = True
161+bankState Goose RightB = True
162+bankState Beans RightB = True
163+bankState _ _ = False
164+
165+bankStateR :: R.Relation Being Bank
166+bankStateR = R.toRel bankState
167+
168+-- Main
169+exec :: IO ()
170+exec = do
171+ putStrLn "Monty Hall Problem solution:"
172+ prettyPrint (secondChoice . firstChoice)
173+ putStrLn "\n Sum of dices probability:"
174+ prettyPrint (sumSSM . kr die die)
175+ putStrLn "\n Conditional dice throw:"
176+ prettyPrint conditionalThrows
177+ putStrLn "\n Checking that the last result is indeed a distribution: "
178+ prettyPrint (bang . sumSSM . kr die die)
179+ putStrLn "\n Probability of grass being wet:"
180+ prettyPrint (grass_wet (state grass sprinkler rain))
181+ putStrLn "\n Probability of rain:"
182+ prettyPrint (rainning . state grass sprinkler rain)
183+ putStrLn "\n Is the arbitrary state a valid state? (Alcuin Puzzle)"
184+ print (inv bankStateR)
test/Examples/Spreadsheets.hsnew file+47
@@ -0,0 +1,47 @@
1+{-# LANGUAGE DeriveGeneric #-}
2+
3+module Examples.Spreadsheets
4+
5+import LAoP.Utils
6+import LAoP.Matrix.Type
7+import GHC.Generics
8+import Prelude hiding (id, (.))
9+
10+data Student = Student1 | Student2 | Student3 | Student4
11+ deriving (Eq, Show, Enum, Bounded, Generic)
12+
13+data Question = Question1 | Question2 | Question3 | Question4
14+ deriving (Eq, Show, Enum, Bounded, Generic)
15+
16+data Results = Exam | Test | Final
17+ deriving (Eq, Show, Enum, Bounded, Generic)
18+
19+test :: Matrix Float One Results
20+test = point Test
21+
22+exam :: Matrix Float One Results
23+exam = point Exam
24+
25+final :: Matrix Float One Results
26+final = point Final
27+
28+m :: Matrix Float Question Student
29+m = fromLists [[95, 90, 100, 40], [20, 90, 90, 0], [30, 20, 95, 0], [50, 80, 100, 30]]
30+
31+w :: Matrix Float Question One
32+w = fromLists [[0.2, 0.3, 0.2, 0.3]]
33+
34+xls :: Matrix Float Question One
35+ -> Matrix Float Question Student
36+ -> Matrix Float Student One
37+ -> Matrix Float (Either Question Results) (Either One Student)
38+xls w m t = join (fork w m) (fork zeros r)
39+ where
40+ rExam = m . tr w
41+ rTest = tr t
42+ rFinal = rTest `maxPW` rExam
43+ r = (rExam . tr exam) + (rTest . tr test) + (rFinal . tr final)
44+
45+-- | Overloaded, point-wise 'max' function
46+maxPW :: Ord e => Matrix e a b -> Matrix e a b -> Matrix e a b
47+maxPW = zipWithM max
test/Spec.hs+7−1
@@ -1,2 +1,8 @@
1+module Main (main) where
2+
3+import qualified Examples.Readme as RD
4+
15main :: IO ()
2−main = putStrLn "Test suite not yet implemented"
6+main = do
7+ putStrLn ("Testing if README works" :: String)
8+ RD.exec