Recursion with anonymous function? #2034
-
Can an anonymous (local) function call itself? I want to use such a function for tail recursion, like so: import gleam/list
pub fn accumulate(l: List(a), fun: fn(a) -> b) -> List(b) {
let inner = fn(data: List(a), acc: List(b)) -> List(b) {
case data {
[] -> list.reverse(acc)
[head, ..tail] -> {
let acc_ = [fun(head), ..acc]
inner(tail, acc_)
}
}
}
inner(l, [])
} But the I guess this would also be solved using the Optional arguments with defaults feature (which isn't there yet right?) in the outer Thank you |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 6 replies
-
Hello! Anonymous functions cannot be recursive, typically a top level private function is used instead. |
Beta Was this translation helpful? Give feedback.
-
Hello, I have been experimenting with Gleam for some time and bumped into this question while trying to implement a tail recursive function of the Fibonacci sequence.
I figured out after some searches that it was impossible to do with Gleam for the time being and had to move the closure to a top level function. Also while searching on this subject, I figured out that Erlang has anonymous named functions since version 17 (see the "Update" section in the middle of the page).
@lpil since Erlang exposes this feature, is there a particular reason for not having it in Gleam? Thanks |
Beta Was this translation helpful? Give feedback.
Hello! Anonymous functions cannot be recursive, typically a top level private function is used instead.