0

I am writing a board game in PureScript that involves a matrix of exact size 2x7 (in certain variations it can be 4x7). The package I’m using has a Matrix.getRow function that returns a Maybe (Array a).

What is the best approach to not have to deal with Maybe returns when I know for sure that Matrix.getRow 0 is always going to return the first row (because the matrix is of fixed size 2x7)?

Currently I have ugly code to deal with Maybes which is obviously not very desirable:

notPossible :: Array Cell
notPossible = [99, 99, 99, 99, 99, 99, 99]  -- never used

row n = fromMaybe notPossible $ Matrix.getRow n state.cells
Sridhar Ratnakumar
  • 81,433
  • 63
  • 146
  • 187

1 Answers1

2

PureScript uses the type system to track partiality, where partiality is the property that a function does not produce a return value for all possible inputs.

If you want to circumvent the type system and guarantee yourself that you will not pass invalid inputs you can use the Partial.Unsafe.unsafePartial :: forall a. (Partial => a) -> a function from the purescript-partial package.

By using the partial function fromJust from Data.Maybe

Data.Maybe.fromJust :: forall a. Partial => Maybe a -> a

you can then construct your unsafe row function:

unsafeRow n xs = unsafePartial fromJust (Matrix.getRow n xs)

You can also delay calling unsafePartial to a point at which you can guarantee that your index is never out of bounds, as the type system will propagate it automatically for you.

Christoph Hegemann
  • 1,434
  • 8
  • 13