Recursion
@PL on
Recursive functions
Let’s define a simple recursive function, which computes the sum from \(0\) to \(n\).
func sum(_ x: Int) -> Int {
if (x == 0) {
return 0
}
else {
return (x + sum(x - 1))
}
}
We cannot define the value in the same way, since the free identifier error occurs.
let sum = { (x: Int) -> Int in
if (x == 0) {
return 0
}
else {
return x + sum(x - 1)
}
}
Now, we define RFAE
, defining recursive functions.
All the materials are from CS320 class held on 2021 spring, KAIST.