TodePond / MotherTode

language language
MIT License
21 stars 1 forks source link

Specify number of repeated term #15

Closed TodePond closed 2 years ago

TodePond commented 2 years ago

It might be useful to be able to specify how many times you want a term to be repeated. Imagine you want to match a hex colour code:

:: "#" HexDigit HexDigit HexDigit HexDigit HexDigit HexDigit

It would be great if you could specify that you want only 6 of them... maybe like this... Not sure what syntax would be best.

:: "#" 6 HexDigit
TodePond commented 2 years ago

Note: This effect can currently be loosely achieved with the 'check' property (??) but it's more complicated. I don't think this is fully correct but it's something like this:

:: "#" HexDigits
HexDigits (
    :: HexDigit+
    ?? ([[digits]]) => digits.length === 6
)
Magnogen commented 2 years ago

Huzzah! I actually tried to implement this, and it worked pretty well. This was my code:

Colour (
    Hex :: /[0-9A-Fa-f]/ >> h => (''+h).toUpperCase()
    :: "#" Hex Hex Hex Hex? [Hex Hex] [Hex Hex]
    >> match => match.source
)

It matches #rgb, #rgba, #rrggbb and #rrggbbaa

With this kind of syntax, it could be simplified to something like

Colour (
    Hex :: /[0-9A-F]/i >> h => (''+h).toUpperCase()
    :: "#" 3 Hex Hex? [2 Hex] [2 Hex]
    >> match => match.source
)
TodePond commented 2 years ago

Yes that looks along the right lines! Cool to see someone else's MotherTode 🤩

Here's another attempt:

Colour (
    Hex :: /[0-9a-fA-F]/ >> hex => hex.output.toUpperCase()
    :: "#" (3 Hex) | (4 Hex) | (6 Hex) | (8 Hex)
)
TodePond commented 2 years ago

(with tabs instead of spaces of course 😅)

Magnogen commented 2 years ago

The way you wrote makes the whole thing make a lot more sense lmao. The IDE I use automatically turns tabs into 2 spaces, so that's my excuse!

TodePond commented 2 years ago

Closing because of upcoming rewrite