An unofficial, read-only Hacker News reader.

Lua as a Query Language (opens external site)

71 points by remywang 9 hours ago | remy.wang | 17 comments on HN

View full thread · View on Hacker News

Comment thread (1)

  1. There has been no shortage of query and SQL-like DSL's in different programming languages; however, when it comes to querying, Prolog is heavily underrated.

    The interesting property of Prolog is that it needs neither a DSL nor a differentiation between input and output parameters at the level of its relational predicates. Joins, filtering, projection and grouping can all also be expressed using native Prolog constructs.

    The same Prolog query can also be run in both directions, including the reverse. That is, if I known the «answer» (i.e. the result), I can ask Prolog to give me an exhaustive set of «questions» that may lead to the «answer».

    The first sample query (named «exhibit1») from the blog post can be rewritten in Prolog thusly (SWI-Prolog is used in the example):

      % The imaginary data model
    
      % lineitem(Order, ShipDate, ExtendedPrice, Discount).
    
      % order(Order, Customer, OrderDate, ShipPriority).
    
      % customer(Customer, MarketSegment).
    
      exhibit1(Price, Discount) :-
        lineitem(Order, ShipDate, Price, Discount),
        order(Order, Customer, OrderDate, _),
        customer(Customer, 'BUILDING'),
        ShipDate #> 19950315,
        OrderDate #< 19950315.
    
    Note that it uses the bog standard Prolog syntax. We can now ask to:

      1. Retrieve all matching prices and discounts:
    
         ?- exhibit1(Price, Discount).
    
      2. Retrieve discounts associated with a price of 200:
    
         ?- exhibit1(200, Discount).
    
      3. Retrieve prices associated with a discount of 10%:
    
         ?- exhibit1(Price, 1r10).
    
      4. Determine whether a particular price-discount combination exists:
    
         ?- exhibit1(200, 1r10).
    
      5. Retrieve prices and discounts subject to additional constraints: 
    
         ?- { Price > 100, Discount < 1/5 },
            exhibit1(Price, Discount).
    
      6. Collect all results into a list:
    
         ?- findall(Price-Discount, exhibit1(Price, Discount), Results).
    
    Note how the query itself («exhibit1») does not change and remains the same for all queries.