Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature request: Scheme-like anonymous recursive functions with initial arguments #7161

Open
ellbur opened this issue Nov 16, 2024 · 1 comment

Comments

@ellbur
Copy link

ellbur commented Nov 16, 2024

In functional languages like rescript, recursion is an important mode of control flow, on par with (or even more important than) loops. For that reason, some languages (like Scheme) have syntactic sugar for creating and immediately calling a recursive function. This reduces the need for complicated (and less flexible) loop syntax.

Motivating example:

type rec tree<'t> = Leaf('t) | Branch(promise<tree<'t>>, promise<tree<'t>>)

let delay = (ms, x) => Promise.make((resolve, _reject) => setTimeout(
  () => resolve(x),
  ms
)->ignore)

let myTree = Branch(
  delay(100, Branch(
    delay(100, Leaf(1)),
    delay(100, Leaf(2))
  )),
  delay(100, Leaf(3))
)

// Current syntax: declare and use a helper function
let rec flatten = async tree => switch tree {
  | Leaf(x) => [x]
  | Branch(x, y) => Array.concat(await flatten(await x), await flatten(await y))
}
let myFlatTree = await flatten(myTree)

// Proposed syntax: anonymous recursive function with initial parameters
let myFlatTree = async rec flatten (tree = myTree) => switch tree {
  | Leaf(x) => [x]
  | Branch(x, y) => Array.concat(await flatten(await x), await flatten(await y))
}
@josher8a
Copy link

I really like it! I think it should be an optional labeled argument. https://rescript-lang.org/docs/manual/latest/function#optional-with-default-value

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants