How to handle formulas with Maybe Numbers

I need to do a bunch of simple math on a collection of number variables. Things like:

x,a,b,c :: MaybeNumber
x = a * (b + c)`

where all of the variable are Maybe Number. I do want to keep the values wrapped in Maybe, even something like

(+) <$> b <*> c

or

do
b' <- b
c' <- c
pure $ b' + c'

is pretty ugly and really hides the formulas, especially when there are multiple terms.

Am I missing something?

Maybe you could try defining functions like

liftedAdd :: forall f a. Apply f => Semiring a => f a -> f a -> f a
liftedAdd = lift2 add

infixr 5 liftedAdd as ^+

liftedMul :: forall f a. Apply f => Semiring a => f a -> f a -> f a
liftedMul = lift2 mul

infixr 6 liftedMul as ^*

and then you can write

x = a ^* (b ^+ c)

You could even go further define the infix operators as + and * and hide the Prelude versions if you have a module where you only want to use the lifted versions.

5 Likes

I think I’m going to try hiding the Prelude versions, for this module, it would be handy to force all formulas to use Maybe Number and the few cases , like constants, where it isn’t, are trivial to handle.

Thanks!

1 Like