Zulip Chat Archive
Stream: Is there code for X?
Topic: String uninterpolation
Leni Aniva (Jan 13 2025 at 17:29):
Is there a function which undoes string interpolation?
For example, suppose I want to test a string (12, 14)
is of the form ({a}, {b})
and a + 2 = b. I need to extract a
and b
and test the equality a + 2 = b
.
Eric Wieser (Jan 13 2025 at 17:34):
Is the string intended to be valid lean syntax?
Leni Aniva (Jan 13 2025 at 17:34):
Eric Wieser said:
Is the string intended to be valid lean syntax?
No
Jireh Loreaux (Jan 13 2025 at 18:01):
Isn't that just parsing? It sounds like you need to write a small parser for the strings relevant to you.
Leni Aniva (Jan 13 2025 at 18:04):
Jireh Loreaux said:
Isn't that just parsing? It sounds like you need to write a small parser for the strings relevant to you.
is there not something similar to scanf?
Kyle Miller (Jan 13 2025 at 19:30):
There's Parsec:
import Std.Internal.Parsec.String
open Std.Internal.Parsec Std.Internal.Parsec.String
class Unrepr (α : Type) where
parse : Parser α
export Unrepr (parse)
instance : Unrepr Nat where
parse := digits
def parsePair : Parser (Nat × Nat) := do
skipChar '('
let a ← parse
skipChar ','
let b ← parse
skipChar ')'
return (a, b)
def parseString (p : Parser α) (s : String) : Except String α :=
match (p <* eof) s.mkIterator with
| .success _ res => .ok res
| .error _ msg => .error msg
#eval parseString parsePair "(1,2)"
-- Except.ok (1, 2)
Kyle Miller (Jan 13 2025 at 19:31):
It shouldn't be too hard of a project to make "parsec strings" like p!"({Nat},{Nat})"
that return a tuple with all the parsed values.
Kyle Miller (Jan 13 2025 at 19:31):
Or maybe p!"({a},{b})"
could be a doElem
that defines a
and b
.
Kyle Miller (Jan 13 2025 at 19:32):
I forgot to generalize parsePair
:
def parsePair [Unrepr α] [Unrepr β] : Parser (α × β) := do
skipChar '('
let a ← parse
skipChar ','
let b ← parse
skipChar ')'
return (a, b)
Last updated: May 02 2025 at 03:31 UTC