How to pattern match 0.0 in SML? [duplicate]

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



How to pattern match 0.0 in SML? [duplicate]



This question already has an answer here:



I have the following code:


datatype complex = RealImg of real * real | Infinity;

fun divisionComplex(RealImg(a, b), RealImg(0.0, 0.0)) = Infinity
fun divisionComplex(RealImg(a, b), RealImg(c, d)) =
RealImg ((a * c + b * d) / (c * c + d * d), ((b * c) - (a * d))/ (c* c + d * d))



However it fails with this:


Error: syntax error: inserting EQUALOP



I am very confused. Why does this happen? I know that I can't compare two reals in SML, but how am I supposed to do pattern matching with 0?



This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.





This question is answered in Why can't I compare reals in Standard ML? under Why won't reals in patterns work [...]? Use an epsilon.
– Simon Shine
Aug 13 at 4:53






Thanks! I've marked it.
– Victor Feitosa
Aug 13 at 15:24




1 Answer
1



As you said SML doesn't allow to pattern match real numbers, but recommends to use Real.== instead or compare the difference between these number against some delta.


Real.==



What about just using a mere if statement for this? (also some Infinity cases added just to make the match against function params exhaustive, but feel free to change it, because it doesn't pretend to be correct)


Infinity


datatype complex = RealImg of real * real | Infinity;

fun divisionComplex(Infinity, _) = Infinity
| divisionComplex(_, Infinity) = Infinity
| divisionComplex(RealImg(a, b), RealImg(c, d)) =
if Real.== (c, 0.0) andalso Real.== (d, 0.0)
then Infinity
else
RealImg ((a * c + b * d) / (c * c + d * d), ((b * c) - (a * d))/ (c* c + d * d))





Thank you! Do you know anyway to match it without the if then else statement?
– Victor Feitosa
Aug 13 at 14:43


if then else





real number can't be matched in sml, since they are inexact and not an equality type
– Igor Drozdov
Aug 13 at 15:10

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

How to determine optimal route across keyboard