5 ms·
Am I missing something subtle? Why would you get a runtime exception if you call this function?
by Athas 6y ago
Am I missing something subtle? Why would you get a runtime exception if you call this function?
- jsmith45 6y agoThe parent missed a part. If you call it with 0 you get an exception, because division by zero obviously.
- yakubin 6y agoNo, you don't. You get Infinity. That's how floating point works.
- smabie 6y agoIn most languages you get an exception
- yakubin 6y agoWhich languages would those be?
- smabie 6y agoI guess I'm thinking of Python mostly. I thought OCaml did as well but apparently not.
- warkdarrior 6y ago$ python3 Python 3.9.1 (default, Feb 3 2021, 07:04:15) [Clang 12.0.0 (clang-1200.0.32.29)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> 10 / 0 Traceback (most recent call last): File "<stdin>", line 1, in <module> ZeroDivisionError: division by zero >>>
- yakubin 6y agoAlthough Python seems to be the exception to the rule here, your example isn't exactly right. In your example, you're performing integer division, not floating point division. In most languages, integer division by zero is indeed some kind of exception (or UB, which will most likely result in a hardware exception, causing a signal sent to the process). However, floating point division by zero is well-defined, as per definition of floating point arithmetic (in some RFCs), and most languages don't throw exceptions in this case. Python indeed seems to be the exception to the rule.
- the_af 6y agoIf you call it with argument 0 you get a runtime exception, because it results in a division by zero. It's "partial" because it's not defined for 0.
- cies 6y agoSo it should have been: Double -> Maybe Double That would be the "right way" to fix this. (or create a type NotNilDouble, lol)
- bidirectional 6y agoOr, controversially, define 1/0 = 0.[1] [1]: https://www.hillelwayne.com/post/divide-by-zero/ https://www.hillelwayne.com/post/divide-by-zero/
- cies 6y agoEnough controversy in defining std libs as it is :)
- the_af 6y agoThe "right" way for division by zero is controversial, though maybe that would be a solution. It's clearer for partial function "head :: [a] -> a", which takes the first of a list if it exists, and explodes without dignity if the list is empty (this is what makes head partial). A proposal is "head :: [a] -> Maybe a", so head returns Nothing when the list is empty.
- cies 6y agoIdris does well here: https://www.idris-lang.org/docs/current/prelude_doc/docs/Prelude.List.html#Prelude.List.head https://www.idris-lang.org/docs/current/prelude_doc/docs/Pre...'
- cies 6y agoIdris does well here: https://www.idris-lang.org/docs/current/contrib_doc/docs/Data.Nat.html#Data.Nat.divMod https://www.idris-lang.org/docs/current/contrib_doc/docs/Dat...