Skip to content

Input/Output/Match-Case/... #30

@patrick-kidger

Description

@patrick-kidger

First of all, thank you for the awesome package.

I've found myself defining some helpers on top of this package for my use-cases, and I'm guessing that some of them might be common enough that others would find them useful too. Would the maintainers of this package be interested in having any of the following upstreamed?

#let Input(doc) = Line([*input* #doc])
#let Output(doc) = Line([*output* #doc]) + Line[$quad$]
#let Sample(var, val) = Line([#var $~$ #val])
#let ForIn(x, xs, code) = For($#x #[*in*] #xs$, code)
#let Case(pattern, code) = (pattern: pattern, code: code)
#let Match(x, ..cases) = {
    if cases.named().len() > 0 {
        panic("`Match` takes only positional arguments.")
    }
    iflike(kw1: "match", kw2: "", kw3: "end", x, {
        for case in cases.pos() {
            if type(case) != dictionary or case.keys() != ("pattern", "code") {
                panic("`Match` should be called with `Case` arguments.")
            }
            iflike(kw1: "case", kw2: "then", kw3: "", case.pattern, case.code)
        }
    })
}
#let Loop(code) = iflike(kw1: "loop", kw3: "end", [], code)
Example document you can copy-paste to see what they look like Copy-paste the following into https://typst.app/play:
#import "@preview/algorithmic:1.0.6": *

#let Input(doc) = Line([*input* #doc])
#let Output(doc) = Line([*output* #doc]) + Line[$quad$]
#let Sample(var, val) = Line([#var $~$ #val])
#let ForIn(x, xs, code) = For($#x #[*in*] #xs$, code)
#let Case(pattern, code) = (pattern: pattern, code: code)
#let Match(x, ..cases) = {
    if cases.named().len() > 0 {
        panic("`Match` takes only positional arguments.")
    }
    iflike(kw1: "match", kw2: "", kw3: "end", x, {
        for case in cases.pos() {
            if type(case) != dictionary or case.keys() != ("pattern", "code") {
                panic("`Match` should be called with `Case` arguments.")
            }
            iflike(kw1: "case", kw2: "then", kw3: "", case.pattern, case.code)
        }
    })
}
#let Loop(code) = iflike(kw1: "loop", kw3: "end", [], code)

#algorithm(line-numbers: false, {
  Input[Some input $x$]
  Output[Some output $y$]
  Sample[$y$][$x$]
  Line[$-----$]
  ForIn($i$, $(1, ..., 5)$, {
    Line[...]
  })
  Line[$-----$]
  Match($z$,
    Case($(a,)$, $a$),
    Case($(a, b)$, $a + b$)
  )
  Line[$-----$]
  Loop({
    Line[...]
  })
})

The only piece I'm not 100% happy with is the unbalanced indentation around match-case-end, happy to take suggestions on this.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions