Can someone explain me how to write this function, which should return the factorial
of x.
The way I tried to do it gives me an error
.
This line is inside a dictionary and refers to Operation.UnaryOperation
that is (Double) -> Double
I tried to write the function I need extensively, It should look like this:
private func factorial(n: Double) -> Double {
if (n<=1) {
return 1
}
return n * factorial(n-1)
}
Now I need to convert it to a single-line function, how do I do it? would it look something like this?, why am I getting an error?
"x!" : Operation.UnaryOperation({if ($0<=1) {return 1} else {return $0 * factorial($0-1)}}),
Just embed the named function in the closure - like this
enum Operation {
case UnaryOperation( (Double) -> Double)
case BinaryOperation( (Double, Double) -> Double)
}
let dictionary: [String: Operation] = [
"+" : Operation.BinaryOperation({ return $0 + $1 }),
"!" : Operation.UnaryOperation({
arg: Double in
func factorial(x: Double) -> Double {
if x <= 1 {
return 1
} else {
return x * factorial(x - 1)
}
}
return factorial(arg)
})
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With