• (disco) in reply to Maciejasjmj

    "Everything should be made as simple as possible, but not simpler." - Albert Einstein.

    Using regular expressions is usually less complicated than writing a parser. It is not that hard to learn them. It just takes a little time and practice.

  • (disco) in reply to coyo
    coyo:
    Using regular expressions is usually less complicated than writing a parser.

    Only because the tools for creating parsers in many languages are needlessly complicated, written by masochistic compiler authors who see no need to cater to plebs who aren't in the business of constructing industrial-grade optimizing compilers themselves.

    Parser combinators make life so much simpler...

  • (disco)

    I actually like Regexes.

    *flamesuit on

  • (disco) in reply to Jaloopa

    It was named after the book. This was the 1960s. Languages didn't need names (or rather, were named after papers/books/their authors).

  • (disco) in reply to mott555

    Regexes are lovely if and only if you're parsing a regular language. Otherwise, they are the wrong tool for the job, and you need something stronger to come up with a robust solution.

  • (disco) in reply to Captain
    Captain:
    Regexes are lovely if and only if you're parsing a regular language.

    Like HTML?


    Filed under: Jeffed!

  • (disco) in reply to Onyx

    Bad ideas thread is :left_luggage: :up: :angry: :large_blue_diamond:.

    On top of being unable to incompletely specify the grammar, abusing regexes in this way is hugely verbose and expensive, especially compared to a LALR parser.

  • (disco) in reply to Captain
    Captain:
    Regexes are lovely if and only if you're parsing a regular language. Otherwise, they are the wrong tool for the job, and you need something stronger to come up with a robust solution.

    What's a "regular language"?

    My main use for Regexes has been the command parser in my MUD. Am I Doing It Wrong™?

  • (disco) in reply to mott555

    As your MUD grows in complexity, you'll hit the limit very soon.

  • (disco) in reply to mott555

    A regular language is a formal language that can be generated or parsed by a deterministic finite automaton (equivalently, it's grammar can be expressed as a regular expression).

    So, about your MUD -- it depends. What is your grammar like? If it's left (or right) linear, regexes are fine. If it has nesting of commands, stop and use a LALR before it becomes expensive (in your time). Honestly, if your commands are more than one or two subcommands deep, I would switch to LALR anyway.

  • (disco) in reply to Captain
    Captain:
    Bad ideas thread is

    Ummm.. Discourse does (did?) that, that's why I said it?

  • (disco) in reply to blakeyrat

    What limit?

    Idk, it's worked well for me so far and it's pretty easy to add new commands in, but everyone's knee-jerk reaction to Regexes is one of hatred. I can't imagine a better way to do what I'm doing so I'm trying to figure out if I'm wrong or if every other developer is wrong.

  • (disco) in reply to mott555
    mott555:
    I can't imagine a better way to do what I'm doing so I'm trying to figure out if I'm wrong or if every other developer is wrong.

    Two better ways have already been offered in this thread:

    tarunik:
    Parser combinators make life so much simpler...
    Captain:
    If it has nesting of commands, stop and use a LALR before it becomes expensive (in your time). Honestly, if your commands are more than one or two subcommands deep, I would switch to LALR anyway.
  • (disco) in reply to mott555
    mott555:
    What limit?

    Well I guess you could design your commands so RegEx will mostly work, other than looking up dynamic keywords from the database. If you allow constructs like 1.plank to identify the first of many planks in the room, you'll outgrow RegEx very quickly. Or end up with a bubbling mess of a codebase. Either/or.

    I mean a really complex MUD might allow a command like:

    emote turns to ~flashy and says, "we have a deal." ~self then looks towards ~rogue and says {elvish} "what a sucker".

    I'm guessing that would be a wide-awake nightmare to implement in RegEx. (Note the two bits of quoted text need to be broadcast to the room in the default and annotated languages, scrambled based on what languages the hearer can understand.)

    The command parser in my old RP MUD was something like 300+ lines. Given, it was shitty C code. But still.

  • (disco) in reply to blakeyrat
    blakeyrat:
    The command parser in my old RP MUD was something like 300+ lines.

    I don't have an easy count for mine, it's modular. There's a class for each command, and each command has a Regex to determine if the input applies and pull the interesting bits out when needed. Then the command parser has a list of commands and tries them one-by-one until one returns that it was successful.

  • (disco) in reply to mott555

    Ok. RegEx still sucks.

  • (disco)

    Yeah, abusing SQL is totally Perl's fault.

  • (disco) in reply to blakeyrat

    The original regexp language was simple and clean. It's grown since, like a syntax cancer, and one of the biggest perpetrators of this… growth… has been Perl, which has been ground zero for Bad Ideas With Regexps for at least 20 years.

  • (disco) in reply to tarunik
    tarunik:
    Parser combinators make life so much simpler...

    Which combinators were you thinking of?

  • (disco) in reply to dkf
    dkf:
    The original regexp language was simple and clean. It's grown since, like a syntax cancer

    You could say the same about SQL. Edgar Codd's baby grew into a beautiful, elegant woman and has now transformed into one of those medieval maps with Heere be Dragons on large sections.

  • (disco) in reply to dkf

    I would suggest a port of Parsec to your language of choice (if it's been ported, of course).

  • (disco) in reply to Captain
    Captain:
    Parsec

    Does that require me to make the Kessel Run?


    Filed Under: Almost-A-Pun

  • (disco) in reply to dkf
    dkf:
    Which combinators were you thinking of?

    I'm not even speaking to a specific implementation -- although one that is close to EBNF syntax is a good idea, IMO.

  • (disco) in reply to Captain

    Interesting. The example has quite a lot of sleight of hand — a bit more than I'd normally expect, especially in the expression handling — but it still looks interesting. Is it taking advantage of Haskell's evaluation scheme to deal with lookahead? (Well, that particular example won't be, and most people try to avoid long lookaheads in their grammars, but in general.)

  • (disco) in reply to blakeyrat
    blakeyrat:
    If you allow constructs like 1.plank to identify the first of many planks in the room, you'll outgrow RegEx very quickly.
    That reminds me of a MUD that allowed you to loot the corpses of monsters that you killed. My MUD client had a macro facility, so every time it saw a monster die it would issue the command `get coins from corpse`. This turned out to be insufficient as soon as there were two corpses in the same room, and even `get coins from all.corpse` wasn't even enough to cut it; I finally ended up with `get all.coins from all.corpse`.

    And then I got banned because I made the mistake of trying to work out what the class restrictions on an item were by wearing it with different characters. (Normally when you wear an item you get told that it's only wearable by a specific class but this item would just say "it is too much extra weight".)

  • (disco) in reply to urkerab
    urkerab:
    And then I got banned

    Nothing to do with getting coins from other people's kills?

  • (disco) in reply to dkf

    No, it doesn't handle backtracking in any "magical" way. You have to explicitly allow for it, using the try combinator.

    The really nice insight is that although parsers can be monadic, EBNF parsers can be expressed in terms of applicative functor combinators (and 'alternative' functors, which are monoids in the category of applicative functors). So you get to use nice notation like:

    expr = startToken *> contents <* endToken
    startToken = char '>'
    endToken = char '\n'
    contents = many alphaNum
    

    or

    -- notice `heading` wraps the heading parsers
    -- in try, since by default, the parser would 
    -- consume the input it succeeded on even if 
    -- it ultimately failed. 
    markdown = heading <|> paragraph <|> code <|> ...
    heading = (try h1) <|> (try h2) <|> (try h3) <|> ...
    h1 = char '#' *> many alphaNum
    ...
    

    There are 'better' applicative parser combinator libraries now (i.e., more suited to specific domains), but Parsec was the first one to use the applicative functors approach. Attoparsec is another library to consider, and has been tuned for high performance on strict Text. But it doesn't have backtracking at all (iirc).

  • (disco) in reply to PleegWat
    PleegWat:
    Nothing to do with getting coins from other people's kills?
    The macro looked for the kill rather than the corpse (if no-one was around I would manually loot corpses anyway just in case) but it did happen once (I gave the money back, although I don't think my victim had any way of telling that I had given them the correct amount).
  • (disco) in reply to urkerab
    urkerab:
    if no-one was around I would manually loot corpses anyway just in case

    Just don't share that on snapchat.

  • (disco) in reply to boomzilla
    boomzilla:
    Just don't share that on snapchat.
    Except in the special combat arena, you couldn't attack, let alone kill, other player characters. (I entered the arena once and scored a very lucky victory; I hadn't noticed that entering the arena de-equipped you of all your armor but fortunately my character was a magic user so once the fighter type had killed everyone else he got a taste of my meteors.)
  • (disco) in reply to tarunik
    tarunik:
    Parser combinators make life so much simpler...

    I found an explanation of parser combinators which actually made sense to me.

    http://theorangeduck.com/page/you-could-have-invented-parser-combinators

  • (disco) in reply to kupfernigk
    kupfernigk:
    Edgar Codd's baby grew into a beautiful, elegant woman and has now transformed into one of those medieval maps with Heere be Dragons on large sections.

    Your SQL metaphor has grown like an acorn into a magnificent Boeing 747.

  • (disco) in reply to PJH
    PJH:
    discourse=# SELECT user_id, id, topic_id, post_number discourse-# FROM posts discourse-# WHERE raw LIKE '%[uid removed]%' AND discourse-# user_id IN ( discourse(# SELECT gu.user_id discourse(# FROM group_users gu discourse(# WHERE group_id IN( discourse(# SELECT g.id discourse(# FROM groups g discourse(# WHERE g.name IN ('admins') discourse(# ) discourse(# );

    Sorry for the very late response to this, just saw the message by accident (Discoursety). I am curious to know how a version using EXISTS would compare.

    In DB2 at least, EXISTS is often much faster than IN, because the latter materializes the entire set while the former only looks for one row (set is not empty). In fact, in the DB2 environment, I rarely use this form of IN because of that. Mostly the savings only materializes if the IN set can be of significant size.

    SELECT user_id, id, topic_id, post_number
    FROM posts po
    WHERE raw LIKE '%[uid removed]%'
    AND EXISTS (
    SELECT gu.user_id
    FROM group_users gu
    WHERE gu.user_id = po.user_id
    AND EXISTS (
    SELECT g.id
    FROM groups g
    WHERE g.id = gu.group_id
    AND g.name IN ('admins')
    )
    );
    

    AIA for any typos.

  • (disco) in reply to CoyneTheDup
    CoyneTheDup:
    Sorry for the very late response to this, just saw the message by accident (Discoursety). I am curious to know how a version using EXISTS would compare.
    SELECT user_id, id, topic_id, post_number
    FROM posts
    WHERE raw LIKE '%[uid removed]%' AND
    user_id IN (
    SELECT gu.user_id
    FROM group_users gu
    WHERE group_id IN(
    SELECT g.id
    FROM groups g
    WHERE g.name IN ('admins')
    )
    );
    
    (10 rows)
    Time: 865.822 ms
    Time: 888.625 ms
    Time: 865.590 ms
    
    SELECT user_id, id, topic_id, post_number
    FROM posts po
    WHERE raw LIKE '%[uid removed]%'
    AND EXISTS (
    SELECT gu.user_id
    FROM group_users gu
    WHERE gu.user_id = po.user_id
    AND EXISTS (
    SELECT g.id
    FROM groups g
    WHERE g.id = gu.group_id
    AND g.name IN ('admins')
    )
    );
    ```
    ```
    (10 rows)
    Time: 862.664 ms
    Time: 899.432 ms
    Time: 834.967 ms
    ```
    
  • (disco) in reply to PJH

    IOW, meaningless performance differences…

  • (disco) in reply to dkf

    In this instance, yup.

  • (disco) in reply to PJH
    PJH:
    > AND g.name IN ('admins')

    Missed one?

  • (disco) in reply to Mikael_Svahnberg

    Prolly. I just copy-pasted the query he wanted to compare with mine...

    Though given it's a literal, not sure how using EXISTS would help with that one, given how much use it was with the rest of the query.

  • (disco) in reply to PJH

    Hence my question mark. Just wanted to be sure that I had not misunderstood anything.

  • Ismaelrof (unregistered)

    Аллюр https://ayurdara.ru/fotoal_bomy/ayurdara_na_vasil_evskom_ostrove/15/

    МАКШИКА 1 (Макшика+Нетра) ПХАЛА – Фруктовый массаж https://ayurdara.ru/fotoal_bomy/ayurdara_-_ayurveda_v_sankt-peterburge/5/1/

    Ещё раз о пользе насьям https://ayurdara.ru/vopros-otvet/rasprodazha_podarochnyh_sertifikatov_spa-programmy_-50_massazhi_i_procedury-_20/

    Дхату – пауштик расаяны: Усиливают оджас, иммунитет и ткани тела https://ayurdara.ru/sredstva_firmy_nagarjuna/kumkumadi_kumkumadi/ Растения, имеющие такие свойства это, к примеру, амла (индийский крыжовник), шатавари (аспарагус рацемозус), шиладжит (индийское мумие), ашвагандха (витания снотворная), паста чаванпраш https://ayurdara.ru/fotoal_bomy/2021/21/ Вайя стхапани расаяны: Увеличивает продолжительность жизни, поддерживает молодость тела и кожи, замедляет старение тела https://ayurdara.ru/sredstva_firmy_kottakkal/indukantam_kvatham_indukantam_kwatham/ Этими качествами обладают семена и ягоды винограда, гранаты, куркума, трифала, дашамула, лотос арабский https://ayurdara.ru/fotoal_bomy/den_jogi_2022/ Медхъя расаяны: Увеличивают интеллектуальные способности и память, убирают стресс https://ayurdara.ru/fotoal_bomy/pattadakal_aihole/8/ В этом нам помогают брами (центелла азиатика, готу-кола), джатамамси (аралия), вача (аир болотный), брами расаяна, сарасвати расаяна https://ayurdara.ru/fotoal_bomy/indijskij_tradicionnyj_centr_zdorov_ya_ayurdara/?p=1 Ваджикарана – аюрведические афродизьяки, увеличивающие либидо и улучшающие качество репродуктивной ткани https://ayurdara.ru/vopros-otvet/_6/ При воздержании — увеличивают интеллект, память и жизненную силу https://ayurdara.ru/ayurvedicheskie_preparaty_himalaya_herbals_indiya/talekt_talekt_himalaya_herbals/ К этим растениям относятся: шатавари, шафран, ашвагандха, индийская роза (она же чайная, бенгальская или китайская), шиладжит, нарасимха расаяна (мужчины), фаласарпис (женщины) и другие https://ayurdara.ru/vopros-otvet/?p=17

    Количество https://ayurdara.ru/fotoal_bomy/ayurdara_na_vasil_evs

  • Gustavodit (unregistered)
    Comment held for moderation.
  • RichardJab (unregistered)

    Желание заказчика — для нас закон https://enli-msk.ru/tproduct/189137735-970766959525-kuhnya-gloss Сделаем столешницы и фасад с закруглениями https://enli-msk.ru/direct/tproduct/500921241-832485839051-kuhnya-modern Не только в горизонтальной плоскости, но и в вертикальной https://enli-msk.ru/tproduct/189137735-313148858291-kuhnya-vudlyuks

    Материал фасада: ЛДСП, Массив Стиль: Дизайнерские, Лофт Цвет: Орех, Серый Столешница: ЛДСП Цена за погонный метр: 54 731 рублей https://enli-msk.ru/direct

    Корпус из 3-х слойного ЛДСП https://enli-msk.ru/direct/tproduct/500921235-374157060731-kuhnya-ribbed

    Цена до акции: 16625 р https://enli-msk.ru/target

    Материал фасада: ЛДСП Стиль: Модерн, Современный Цвет: Орех Столешница: ЛДСП Цена за погонный метр: 59 940 рублей http://enli-msk.ru

    Доработка дизайн-проекта в течение 2-3 суток https://enli-msk.ru/

  • CharlesDal (unregistered)

    Поскольку изделие симметричное, то достаточно сделать лекало 1?2 части https://materline.ru/catalog/mattress_toppers/ Выкройка подушки для беременной показана ниже https://materline.ru/catalog/mattresses/comfort/dolce_luna/ При желании вы можете корректировать размеры https://materline.ru/catalog/pillows/saponetta/

    В сегодняшнем уроке предлагаем вам заняться https://materline.ru/catalog/mattresses/lux/dolce_luna_multipaket/ Это одно из самых приятных занятий для каждой женщины https://materline.ru/catalog/mattresses/duet/ Автор мастер класса Мария Старикова расскажет вам, как сшить традиционную подушку по всем ремесленным канонам https://materline.ru/catalog/mattresses_for_babys/ Она имеет круглую форму (наподобие каравая из печи) и сшита из ситца https://materline.ru/catalog/mattresses/lux/laura/ А еще дополнена красивой незатейливой аппликацией https://materline.ru/contacts/ Такую и под голову можно положить и на стул для большего комфорта https://materline.ru/catalog/mattresses/lux/

    Считаю что подушка для кормления в наше время уже необходимость https://materline.ru/catalog/mattresses/lux/dolce_luna_multipaket/ Все мы щас подстраиваемся под современные технологии которые нам облегчают воспитание малыша https://materline.ru/contacts/ Я пользовалась подушкой для кормления от фирмы эргофид http://materline.ru Это было спасением для моих рук и спины, на нее положил малышку и она кушает https://materline.ru/catalog/mattresses/comfort/dolce_luna/

    У меня все, надеюсь помог!? Спасибо за внимание, и за то, что осилили такой объем информации https://materline.ru/catalog/mattresses_for_babys/ До новых встреч на Вопрос Авто, берегите себя и свой автомобиль https://materline.ru/catalog/mattresses/ Пока https://materline.ru/catalog/pillows/saponetta/

    Неисправные подушки — распространенное явление особенно в автомобилях с большим пробегом https://materline.ru/catalog/ Не работать они могут по нескольким причинам, например, в связи с истечением срока пригод

  • MatthewReavy (unregistered)

    КПБ Мако-Сатин 3D артикул 1001 http://sklad46.ru

    Простынь размеры см, (шт) Размерный ряд постельного белья из мако - сатина: Либо Вы можете воспользоваться нашим интернет-магазином https://sklad46.ru/uslugi/podushki/ Вся продукция компании, в том числе и новинки, представлены в Каталоге https://sklad46.ru/kompaniya/partnery/ Делайте заказ, и мы отправим его транспортной компанией в Москву в течении 3х рабочих дней https://sklad46.ru/uslugi/tumbochki-i-shkafy/ Подробности Вы можете узнать на страницах Условия работы и Доставка https://sklad46.ru/uslugi/matrasy/po-tipu/porolonovye/

    Расширяя рынок сбыта, мы налаживаем партнерство с ведущими транспортными компаниями https://sklad46.ru/uslugi/odeyala/ Купить продукцию в Иваново может каждый независимо от того, где сосредоточен бизнес https://sklad46.ru/kontakty/politika-konfidentsialnosti/ Ориентируясь на европейский уровень обслуживания, мы стараемся, чтобы сотрудничество с ивановской фабрикой было для клиента не только выгодным, но и удобным https://sklad46.ru/uslugi/polotentsa/polotentsa-dlya-spa-salonov/

    Лукас поплин https://sklad46.ru/uslugi/podushki/

  • Glennnek (unregistered)

    К преимуществам магазина можно отнести: Исключительно все жаждут уверенности, что приобретают продукцию высочайшего качества https://акваторг24.рф/zapornaya-radiatornaya-kotelnaya-armatura/kollektor-iz-nerzhaveyuschey-stali-dlya-teplogo-pola-3-kontura-tim-art-kcs5003/ Наш интернет-магазин сантехники гарантирует это https://акваторг24.рф/product/diametr-truby-v-dyuymah/2-1-2/

    …теперь это коснулось и сантехники https://акваторг24.рф/gruppy-bezopasnosti/kronshteyn-gruppy-bezopasnosti-du25/ Нашел интернет – магазин сантехника онлайн https://акваторг24.рф/polipropilenovye-truby-slt-aqua-polipropilenovye-truby-slt-aqua/polipropilenovye-truby-armirovannye-1/armirovannaya-steklovoloknom-truba-slt-aqua-pp-r-pp-r-gf-pp-r-d63x10-5-sdr6-4-m-sltpgf66325/ Вполне достойный магазин, есть все что надо и цены терпимые https://акваторг24.рф/truby-i-fitingi/hromirovannyy-troynik-latunnyy-tim-1-2-x1-2-x1-2-art-k-tfmf222/

    Официальный сайт: santehmoll https://акваторг24.рф/product/tip-rezby/2f/ ru https://акваторг24.рф/truby-i-fitingi/svarochnyy-apparat-dlya-trub-i-fitingov-ppr-1800-vt-tim-wm-02/

  • Williamtob (unregistered)
    Comment held for moderation.
  • ScottNef (unregistered)
    Comment held for moderation.
  • Ernestchamy (unregistered)
    Comment held for moderation.
  • Davidscuse (unregistered)
    Comment held for moderation.
  • AlbertoSaill (unregistered)
    Comment held for moderation.

Leave a comment on “A Shining Perl”

Log In or post as a guest

Replying to comment #:

« Return to Article