Skip to content

Destructuring pattern matching with as patterns #8296

@stochastical

Description

@stochastical

Description

Both Haskell and Rust support "as" patterns, where you can perform destructuring and binding at the same time:

contrivedMap :: ([a] -> a -> b) -> [a] -> [b]
contrivedMap f [] = []
contrivedMap f list@(x:xs) = f list x : contrivedMap f xs

Here, list is bound to the entirety of the list argument, and x and xs are bound to the head and tail elements, respectively.

Use Case

It'd be nice (but by no means critical!) if Typst could support as pattern too.

I think the utility here might only come into play with custom types support.
But the request comes from a statistics library I've been working on in Typst:

/// Generates a random variate from the binomial distribution using inverse transform sampling.
///
/// - `(n: n, p: p)` (pattern): A dictionary representing the Binomial distribution
/// - u (float): A uniform random variate in the range [0, 1)
/// -> int
#let sample((n: n, p: p), u) = {
  assert(u >= 0.0 and u < 1.0, message: "Uniform random variate " + str(u) + " must be in the range [0, 1).")
  let k = 0
  let cumulative = cdf((n: n, p: p))(k)
  while cumulative <= u {
    k += 1
    cumulative = cdf((n: n, p: p))(k)
  }
  k
}

I'm using the sample((n: n, p: p), u) to restructure the Binomial dictionary object in the function signature, but end up passing it through to the cdf function as a whole. Here, I could just use a dictionary without destructuring: it's really just a hacky way to enforce (very loose) 'type safety'.

Metadata

Metadata

Assignees

No one assigned

    Labels

    feature requestNew feature or requestscriptingAbout Typst's coding capabilitiessyntaxAbout syntax, parsing, etc.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions