I am wrapping some matrix library from javascript into Purescript. And I am thinking which signatures my two creation functions for a matrix should have. Their main difference is that in one case you just give a Vector (JS Array) and in the other case you give a 2D Array. In the first case I can easily construct my Matrix. But in the second case I have a error condition to check as the array elemements of of the 2D array (themselves being arrays) all need to be of the same lenght.
data Matrix = Matrix (Array (Array Number))
data Err = Err -- just some error, really not import what kind
make :: (Array (Array Number)) -> Either Err Matrix
make xs = if internalSizesCorrect xs then Right $ Matrix xs else Left Err
make' :: Array Number -> Matrix
make' xs = Matrix [xs]
This is easy but also sort of ugly as make
and make'
have completely different return types.
The easiest solution of course would be
make'' :: Array Number -> Either Err Matrix
make'' xs = Right $ Matrix [xs]
Well ... no!
Another option could be to merge the error condition into the type itself so that
data Matrix = Matrix (Array (Array Number))
| MatrixErr
make :: (Array (Array Number)) -> Matrix
make xs = if internalSizesCorrect xs then Matrix xs else MatrixErr
make' :: Array Number -> Matrix
make' xs = Matrix [xs]
But I havent seen such things yet in the Purescript/Haskell. So I am not sure if this is really a good idea