java – 函数式编程:如何处理函数式编程中的异常或它的等价物
发布时间:2020-05-24 19:45:04 所属栏目:Java 来源:互联网
导读:让我们说,我有以下代码. public int divide(int dividend, int divisor) { if( divisor == 0 || (dividend == Integer.MIN_VALUE divisor == -1)) throw new DivisionException(); return dividend/divi
|
让我们说,我有以下代码. 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玩它 在Haskell中,您可以将错误抛出错误“和您的错误消息”,但这会让您崩溃程序……这不是我们想要的. (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
