Java – Functional Programming: how to handle exceptions or their equivalents in functional programming
Let's say I have the following code
public int divide(int dividend,int divisor) { if( divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1)) throw new DivisionException(); return dividend/divisor; }
How to write in functional programming?
I have a function code similar to the logic written in Java above and hope to migrate it to Haskell / clojure How to deal with split callers?
I know the above code is absolutely necessary It is not pre - written to migrate it to FP in the future
Please tell me with sample code in Haskell or clojure
Solution
The following shows how to do it in Haskell
Based on the type siginure divide:: int – > int – > regardless of [char] int, you can see that the function division will return a left string or right int
Or algebraic data structures, and more, you can write it yourself
divide :: Int -> Int -> Either [Char] Int divide dividend divisor | (divisor == 0) = Left "Sorry,0 is not allowed :o" | (dividend == (minBound :: Int)) && (divisor == -1) = Left "somethig went wrong" | otherwise = Right (dividend `div` divisor) main = do print (divide 4 2) -- Right 2 print (divide 4 0) -- Left "Sorry,0 is not allowed :o" print (divide (minBound :: Int) (-1)) -- Left "somethig went wrong"
You can do it in repl It play it
In Haskell, you can throw the error "and your error message", but it will make you crash the program... This is not what we want