I'm new to ML, and a bit of my code isn't working. I'm creating a function in ML where it's supposed to sort reals and then compile them into a single list. I created a large if-then statement, but it keeps failing at one particular point and I can't figure out why.
Here's my code:
fun sort3(c: real, g: real, j: real) =
if c < g andalso g < j then [c, g, j]
else if c < g andalso g > j then [c, j, g]
else if c > g andalso c < j then [g, c, j]
else if c > g andalso c > j then [g, j, c]
else if c > g andalso g > j then [j, g, c]
else [j, c, g];
When I submit 3 real numbers into them, I expect to get them sorted from least to greatest. Most of the time, this is true, with two major exceptions. I'll write my results down below (all of them are real, not int).
- (1,2,3) = (1,2,3)
- (3,2,1) = (2,1,3) X
- (2,1,3) = (1,2,3)
- (3,1,2) = (1,2,3)
- (2,3,1) = (2,1,3) X
- (1,3,2) = (1,2,3)
Is there something wrong with my code? Is ML particular about using too many if-then statements? Thank you in advance!
Looking at your code, you've made some bad assumptions:
This holds up.
This one not so much. We know from your conditional expression that
cis less thang, and thatjis less thang, but this does not tell us anything about the relationship betweencandj.This logic holds up.
We know from this that both
gandjare less thanc, but not howgandjrelate to each other.This logic works.
A different way to approach this might be with nested conditionals, establish first which is the smallest, at which point there are only two values to compare.