Zulip Chat Archive

Stream: general

Topic: sscanf macro


Conor Bergin (Dec 13 2023 at 16:44):

Is it be possible to write a macro like sscanf!"{String}: {Nat} - {Nat}" that would return an Option (String x Nat x Nat) the tuple type being the same as whatever was in the format string? Rust has a crate for this which I use a lot and I would like to have it in lean.

Conor Bergin (Dec 13 2023 at 16:45):

https://docs.rs/sscanf/latest/sscanf/

Kyle Miller (Dec 13 2023 at 18:02):

Yeah, you should be able to write such a macro without too much work. You could use interpStr to parse these curly brace strings in a general way, but you'd have to figure out how to encode parsing options somehow.

Kyle Miller (Dec 13 2023 at 19:10):

@Conor Bergin Here's a prototype:

code

Kyle Miller (Dec 13 2023 at 19:11):

A couple examples:

#eval (parsec!"{String}: {Nat} - {Nat}").run "entry1: 1 - 2"
/-
Except.ok ("entry1", 1, 2)
-/

-- This works too:
#eval (parsec!"{}: {} - {}" : Parsec (String × Nat × Nat)).run "entry1: 1 - 2"

Kyle Miller (Dec 13 2023 at 19:12):

This theoretically supports radix specifiers like {Nat : r16} but I didn't implement this part.

Kyle Miller (Dec 13 2023 at 19:23):

Here's an example of extensibility:

structure Color where
  (r g b : Nat)
  deriving Repr

instance : ParsecParse Color where
  parse _ := do
    let (r, g, b)  parsec!"({},{},{})"
    return {r, g, b}

#eval (parsec!"color = {Color}").run "color = (1,2,3)"
/-
Except.ok { r := 1, g := 2, b := 3 }
-/

Conor Bergin (Dec 13 2023 at 19:30):

This looks great, I wasn't expecting a working prototype within an hour! I am still working through the macro docs so it'll take me a bit to understand all of this.


Last updated: Dec 20 2023 at 11:08 UTC