A few years ago I had an idea of writing functions as simple as Excel, but with extra safety.
I came unstuck for several reasons, but division seemed a nice nugget which never sat well with me.
There are several ways to do division here:
The idea is to search for something safe which an Excel user could use.
E.g. this might be idiomatic:
safeDiv :: (Eq a, Fractional a) => a -> a -> Maybe a
safeDiv _ 0 = Nothing
safeDiv x y = Just (x / y)
doEx :: (Eq b, Fractional b) => b -> b -> b -> Maybe b
doEx a b c = do
a' <- a `safeDiv` b
a' `safeDiv` c
but, I found this more appealing:
maybeDiv :: (Eq a, Fractional a) => Maybe a -> Maybe a -> Maybe a
maybeDiv (Just n) (Just 0) = Nothing
maybeDiv (Just n) (Just d) = Just (n / d)
maybeDiv Nothing _ = Nothing
maybeDiv _ Nothing = Nothing
maybeDivEx :: (Eq a, Fractional a) => a -> a -> a -> Maybe a
maybeDivEx a b c = Just a `maybeDiv` Just b `maybeDiv` Just c
I.e. the operations can be chained together with minimum fuss (like any nice algebraā¦). I imagine the maybeDiv
function could be hidden away in a library out of sight.
But of course, itās domain specific (e.g. simple calculator) and doesnāt have the general type definition that Haskellers love.
Any other ideas?
I am thinking about a Liquid Haskell exampleā¦ Unsure whether it would really help much thoughā¦ Curious.