Functional programming: how to handle exceptions in functional programming or what is equivalent

Say I have the code below.

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 it in functional programming?

I have logic similar to the one described above written in Java, and I would like to port it to functional code in Haskell / Clojure. How to handle this in callers divide?

I know that the code above is absolutely necessary. It was not written with forethought about porting it to FP in the future.

Please give me sample code in Haskell or Clojure.

+6
source share
3 answers

, Haskell.

siginure divide :: Int -> Int -> Either [Char] Int , divide Left string, Right Int.

Either - , , .

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"

repl.it

Haskell error "and your error message", .. , .

+11

Clojure Java:

(defn divide
  [dividend divisor]
  (if (or (zero? divisor)
          (and (= Integer/MIN_VALUE
                  dividend)
               (= -1 divisor)))
    (throw (DivisionException.))
    (/ dividend divisor)))

, , . Clojure, JVM.

+2

divide : .

total

, , . , .

, Clojure, nil, , . , Haskell, Data.Either , .

  • Haskell. , , . -, must-divide, .

  • Clojure nil - , , , . , divide, , :

    (divide x y :on-error (throw ...))
    (divide x y :on-error default-value)
    

    ... :

    (or (maybe-divide x y) (throw ...))
    (or (maybe-divide x y) default-value)
    

    ...

    (defn maybe-divide [dividend divisor]
      (and (not (zero? divisor)) 
           (or (not= Integer/MIN_VALUE dividend)
               (not= -1 divisor))
           (/ dividend divisor)))
    

: . , , divide , , (, - , , - null). Clojure Haskell . , .

+2

All Articles