factorial function input int, output real?
Question
This is absolutely driving me nuts. The supposed simplest thing I can imagine and I can't do it.
I just want to computer factorial inputting an int and output a real.
I've tried to coerce in numerous way.
fun factorial 0 = 1 |
factorial n = n * factorial(n-1);
Solution
To convert an int to a real, you use Real.fromInt
. If you want to return reals, you should also return 1.0
instead of 1
as the base case. So your code becomes:
fun factorial 0 = 1.0
| factorial n = (Real.fromInt n) * factorial(n-1);
OTHER TIPS
Mathematically, n! = (n-1)! * n . Unless i'm misunderstanding things (which is possible; i don't know ML), your function will always return 1 because it's never multiplying by n.
fun factorial 0 = 1 |
factorial n = n * factorial(n-1);
I don't know how you return a real rather than an int, or whether this code even does it, but at the very least it should give you a correct value.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow