Home > Blockchain >  Is there a total div alternative in Haskell prelude?
Is there a total div alternative in Haskell prelude?

Time:10-07

I'm looking for something which wraps the div into Maybe. I want to specifically know if there is a thing for it in prelude, since I'm working on a uni assignment, and we cannot use modules other than prelude. I can make a lambda, but why make a lambda if it already exists. Lambda in function composition looks ugly.

I've also realized that what i can do i guess is to use division <$> Maybe divisor. Now that in turn makes me wonder if maybe a function to check equality and if equal return Nothing exists.

CodePudding user response:

You could do your own:

-- does division, returns Nothing if divisor is zero
tdiv :: Integral a => a -> a -> Maybe a
tdiv x y
   | y == 0 = Nothing
   | otherwise = Just (x `div` y)

main = do 
    print $ 2 `tdiv` 1
    print $ 1 `tdiv` 0
  • Related