一個東西可以用它自己來定義,這種能力就叫做遞迴。在 Gleam 中,遞迴最常出現在遞迴函式裡,也就是會呼叫自己的函式。
遞迴函式至少需要一個_基礎情況_,以及至少一個_遞迴情況_。_基礎情況_會回傳一個值,而不會再次呼叫函式。_遞迴情況_會再次呼叫函式,並調整輸入,讓它在某個時間點符合基礎情況。
pub fn factorial(x: Int) -> Int {
case x {
// Base case
1 -> 1
// Recursive case
_ -> x * factorial(x - 1)
}
}
Gleam 沒有專門用來迴圈的語法,所以所有的迴圈都是用遞迴完成的。
pub fn list_length(list: List(String)) -> Int {
case list {
[] -> 0
[_, ..rest] -> 1 + list_length(rest)
}
}
Gleam 也支援遞迴自訂型別。遞迴自訂型別的其中一個或多個變體,會在自身包含的資料中參照自己。
pub type RussianDoll {
Child // Base case
Mother(RussianDoll) // Recursive case
}
let very_big_doll = Mother(Mother(Mother(Child)))
let small_doll = Mother(Child)