让我们说,我有以下代码.
public int divide(int dividend,int divisor) { if( divisor == 0 || (dividend == Integer.MIN_VALUE && divisor == -1)) throw new DivisionException(); return dividend/divisor; }
如何在函数式编程中编写?
我有一个类似于上面用Java编写的逻辑,并希望将其迁移到Haskell / Clojure中的功能代码.
如何处理分裂的来电者?
我知道上面的代码是完全必要的.它不是在未来将其迁移到FP的预先编写的.
请在Haskell或Clojure中使用示例代码告诉我.
解决方法
以下显示了如何在Haskell中完成它.
基于类型siginure divide :: Int – > Int – >无论[Char] Int,您都可以看到函数除法将返回Left字符串或Right Int.
要么是代数数据结构,还有更多,你可以自己编写.
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玩它