Join the discussion

Write your take first — we'll ask for email only when you're ready to publish.

  • Hacker News
  • Well, with respect to Markus Triska, I don't like purity. Prolog gives you plenty of "impure" constructs like the cut (!/0) and the assert/retract family of database manipulation predicates. It also gives you impure I/O and arithmetic functions that are quite separate from the otherwise logical, declarative-ish style of the language.

    I'm fine with all that. The language gives you sensible tools to deal with edge cases that otherwise require you to jump through hoops or import libraries (like the constraint arithmetic libraries that Markus recommends... and that he had to mostly write himself before he could recommend). You can get into a spot of bother if you use those facilities without knowing why they are there and why you shouldn't just spam them in every case, but that's why good textbooks exist.

    And more to the point, that's why Prolog Coding Guidelines are a thing, more precisely, a paper, which you can find here from the website of Michael Covington who's one of its (many) authors:

    https://www.covingtoninnovations.com/mc/plcoding.pdf

    Here's what the Guidelines has to say about assert/retract:

    5.10 Avoid asserta/assertz and retract unless you actually need to preserve information through backtracking Although it depends on your compiler, asserta/assertz and retract are usually very slow. Their purpose is to store information that must survive backtracking. If you are merely passing intermediate results from one step of computation to the next, use arguments.

    If you have a dynamic predicate, write interface predicates for changing it instead of using “bare” calls to asserta/assertz and retract, so that your interface predicates can check that the changes are logically correct, maintain mutexes for multiple threads, and so forth.

    Sound advice. In fact that's what I've always done myself even before reading the Guidelines.

    And here's some advice on using the "horror" of the cut without having to wake the Great Old Ones:

    5.4 Use cuts sparingly but precisely First think through how to do the computation without a cut; then add cuts to save work. For further guidance see O’Keefe (1990, pp. 88–101). Concerning code layout, make sure cuts do not go unnoticed: if a green cut7 may be placed on the same line as the previous predicate call, red cuts definitely must be on their own line of code.

    5.5 Never add a cut to correct an unknown problem A common type of Prolog programing error is manifested in a predicate that yields the right result on the first try but goes wrong upon backtracking. Rather than add a cut to eliminate the backtracking, investigate what went wrong with the logic. There is a real risk that if the problem is cured by adding the cut, the cut will be far away from the actual error (even in a different predicate), which will remain present to cause other problems later

    Basically the message should be that we can help the novice to navigate the complexities of the language without underestimating or pataronising them. Cuts, asserts, and the lot, are just there to make things easier. They only make things harder when they're not explained properly. And telling everyone to just stay away from them is, I think, not the proper way to explain anything.

  • I kind of agree with both of you. I would have become better at Prolog faster if I had stuck to the discipline Triska promotes early on, but I also think the guidelines you cite are reasonable once one is starting to do somewhat productive work where compromises and speed factors in.

    Over the years I've come to a similar position in other languages as well. If a functional-ish solution fits performance constraints and is maintainable, don't mutate or reach for global state, things like that.

  • Would a Prolog expert please explain the difference between > and #>, is and #=, and what ! does?

    The version without ! looks identical to the version with ! except only the ! is removed - is this a joke?

  • >> The version without ! looks identical to the version with ! except only the ! is removed - is this a joke?

    That's just showing getting rid of the cut in two stages. The line that makes it possible to remove it is this one:

    N #> 0,

    Markus Triskas' argument is that if you use the #> etc versions of declarative arithmetic operators, instead of the > ones, you can then call the factorial predicate with both arguments as variables, i.e. without inputs, just outputs, to enumerate the entire factorial relation. Like this:

      ?- n_factorial(N, F).
         N = 0, F = 1
      ;  N = 1, F = 1
      ;  N = 2, F = 2
      ;  N = 3, F = 6
      ;  ... .
    
    If you use > instead of #> the line N > 0 will raise an exception if N is a variable, which will be the case if you call it as above. This stops you from enumerating the relation, which declarative arithmetic allows.

    Of course there are other ways to write a factorial predicate (or any predicate) so that it always enumerates a relation but they are more verbose. Then again, you do need a special library to use declarative arithmetic anyway, so.

  • !/0 is the cut. It prunes the search space. Useful to say "do not look at the other alternatives since I know they will fail" (when mutually exclusivity is hard) but also necessary to do negation in Prolog (when negated information cannot be easily or efficiently propagated).

    is/2 is arithmetic evaluator. It runs only in one direction and it does not solve equations.

    #>, #=, etc. are constraints, like (in)equalities over linear arithmetic. When constraints have the form of some known theory (like in SMT solvers), they can be solved (incrementally). That is called "constraint logic programming" (CLP). Modern Prolog systems are indeed CLP systems.

    Prolog is older than CLP. CLP is older than SMT. Prolog+CLP systems are turing complete, can be used as programming languages. SMT is powerful but not a programming language.

    Can "impure" features be avoided? Not in all cases. Think of them as 'unsafe' in Rust, but less dangerous.

    Markus pushes for more purity in Prolog (using CLPFD), but sometimes some impurity (or imperative-like code with side-effects) is the best solution. Sometimes the pure solution is also the better. In other cases, it is not. Better compilers and static analyzers can reduce the friction between these worlds.

    Take away: do pure code if you can afford it and it looks like a natural solution to your problem, use impure features later if you really need them.

    by jfmc
  • Prolog operators like `4 > 5` are a syntax sugar which desugars into a normal function call `>(4, 5)`. This part of the language is programmable, so you can add your own function `#>(X, Y)` and then declare it as an operator and use it like `4 #> 5`. See [1]. Nitpickingly, this means we can't be sure what #> is without looking, but it's common in Scryer and SWI Prolog (at least) that the #> #< versions of numeric comparison operators are used by constraint solver libraries. In imaginary Python it might be this code:

        import solver
    
        solver.add_variable(x)
        solver.variable_range(x, 0, 100)
        solver.add_constraint(x, greater_than, 50)
    
        solver.solve_for(x)
    
    in pseudo-Prolog it can be:

        :- using constraint solver library
        
        X in 0..100,
        X #> 50,
    
        label(X)
    
    where "in" and "#>" were added into the language at runtime by the import of the constraint library. That is, it calls out to a custom 'function' which tells the constraint solver to restrict possible values for for X from 0..100 down to 51..100.

    > "and what ! does"

    This is a concept which doesn't translate easily to other languages, but analogously it's like the performance difference between this code which always searches the entire haystack:

        found = false
        for item in haystack:
            if item == 'needle':
                found = true
    
        return found
    
    and this which stops searching the haystack if the needle is found, but still searches the entire haystack in the worst case:

        for item in haystack:
            if item == 'needle':
                return true
    
        return false
    
    The catch being that ! is not exactly a performance thing, it's an instruction to the Prolog runtime to skip some of the code, which can speed up performance but if you throw it in carelessly, your code no longer gives the right answers.

    [1] They aren't Prolog "functions", they are predicates, functions are different, but it will do for this explanation.

  • I get what he's saying but I think it's overstated. I'd categorise his list as "Things to be careful with" not "Coding horrors". For example, "The primary means to make your programs defective in this way is to use predicates like assertz/1 and retract/1" is an unqualified statement that makes it sound like you should never ever use them, and that's not the case. I have a real-life Prolog app that applies rules to facts read from JSON data files. I could do that two ways:

    1) Read the JSON with Prolog (there's a library) and assertz() the facts from that, building an immutable database in the first phase before applying the rules in the second phase.

    2) Externally transform the JSON into Prolog facts, load that into the app on startup and apply the same rules to it.

    I agree that mutating the database in the second phase is probably a bad idea, but that's not the same as saying "assertz() always bad". I'd read his site before it appeared on HN and whilst there a lot of very good stuff on it, some of it reminds me of FP purist edicts - fine if you want to go that way and it's appropriate to your problem, but that isn't always going to be the case. That was the basis of my earlier (downvoted) "Mostly overblown" comment.

    But nice to see Prolog mentioned at all on HN :-)

  • I've never seen Prolog used at all in the wild, but OPA (and its ancestor, Datalog) are fairly common.
  • We need infinity-Prolog, which already knows all known facts. Feeding them separately everytime feels lame.
  • I haven’t used Prolog, but I have a little experience with Erlang and a lot with Elixir. As I understand it, the early versions of Erlang were inspired by Prolog.

    For those with familiarity with both Prolog and Erlang, can you comment on the similarities and differences between? Is/was Erlang basically Prolog with OTP bolted on?

  • These two languages are completely different paradigms.
  • What Joe Armstrong et al took from Prolog is mainly the syntax.
  • Not familiar with Erlang that much, but it's pretty clear Erlang was prototyped on Prolog because of its convenient facilities for DSLs using op/3 to define new tokens for its built-in bottom-up expression parser (using operator precedence parsing) and its Definite Clause Grammar recursive descent parser as trivial specialization of core SLD resolution (Prolog was created for NLP and planning apps in the first place after all).

    I guess what may also have contributed is that there are a number of concurrent logics implemented in Prolog for prototyping Erlang's scheduler such as Concurrent Transaction Logic ([1]).

    [1]: https://www.cs.toronto.edu/~bonner/ctr/Home.html

  • Erlang has very little in common with Prolog, which is a language in an entirely different paradigm (logic programming).

    Early versions of Erlang were implemented in Prolog, which is why Erlang's syntax looks a whole lot like Prolog's, but beyond that they're not very similar.

  • Super simple example

        % Prolog
        next_light(green, yellow).
        next_light(yellow, red).
        next_light(red, green).
    
        % Erlang
        next_light(green)  -> yellow;
        next_light(yellow) -> red;
        next_light(red)    -> green.
    
    Notable differences:

    - `;` in Erlang indicates multi clause function

    - In Prolog next_light is database, in Erlang it's just a function

    Question: What's the light before green?

        % Erlang
        % Returns actual value
        prev_light_search() -> 
        [State || State <- [green, yellow, red], next_light(State) == green].
    
        % Prolog (?- means that it's in query mode)
        ?- next_light(Light, green).
    
    
    So syntax IS similar though the thing is that Prolog is more like binding and quering database and Erlang is executing function.

    In a nutshell Erlang is more like: "when I have X, then I can calculate Y" and Prolog like "If I want Y, what's the X".

    by xlii
  • There's something quite illuminating with this first "horror", where they basically say "it's OK to report wrong answers, because you can check the answers".

    I don't think I've ever felt like it's OK for my program to provide a list of answers where some are right and some are wrong, but reading this... and generally believing in P != NP.... maybe that's a decent way of looking at some stuff!

    by rtpg
  • The article server is offline, but I assume they found out that prolog rule evaluation depends on the order the rules are presented in the program.

    If so, the language they thought they were using (and that they should actually use) is datalog, not prolog.

    Datalog has declarative semantics: All facts that are derivable from the base database and the rules will be derived by the interpreter, and it will not add extra hallucinated facts. If that's not true, it's a bug in the runtime, not in the language.

  • iirc, shor's algorithm for factoring relies on this.
  • Sometimes the Biorhythm program on my Apple ][ failed to produce correct answers. But it sure was great for impressing cool hippie chicks.

    https://www.youtube.com/watch?v=jYoY1cwAd90

  • I've actually run into this in the wild, with regards to sales forecasting. A program we were using returned zero if the error bars on a forecast were over 100%. For example, selling somewhere between 1 and 7 units, but averaging 3.

    Returning 3 was "wrong", but infinitely more correct than retuning 0.

  • If you want to understand prolog, you must understand the four-port model:

    https://grack.com/writing/school/enel553/report/prolog.html

  • And to understand the four-port model is to understand solution-space navigation and pruning.
  • What do people use Prolog for in the real world? I learned about it on a university course and it seems so esoteric compared to other things on the course. Like something invented just for computer scientists to enjoy.
  • The JS package manager Yarn had an experimental feature to define dependency constraints using prolog, it made for very concise way to represent the logic.

    https://v3.yarnpkg.com/features/constraints

    It never got released for good though. I actually had need of such feature for a project but I thought that using an exoteric programming language and an experimental feature was a bit much. I ended up setting up those constraints as a CI check hand-made script and the code was surprisingly large (~300 lines), but not that hard to understand.

  • Some applications were discussed in https://news.ycombinator.com/item?id=40994552
  • Many years ago Maemo (the mobile OS from Nokia) had the profile manager (day mode/night mode etc) written in Prolog. To me it seems like it's a very appropriate application for it.
  • "Planning, optimization, diagnostics, and complex configuration" [1]

    Prolog also works extremely well as a target language for code generation by LLMs for these domains due to it being "higher up in the food chain" compared to procedural languages so to speak, and because Prolog was originally envisioned for classic NLP and hence has a corpus of one-to-one mappings from natural language to logic (as in the example in [3]). So well in fact that even with last-gen models textual descriptions for suitable problems become the bottleneck and you can in many cases just go straight to Prolog code instead ([2]).

    [1]: https://quantumprolog.sgml.net

    [2]: https://quantumprolog.sgml.net/llm-demo/part1.html

    [3]: https://news.ycombinator.com/item?id=48080201

  • 20+ years ago, it was the backend for the business rules engine that processed various logging and monitoring events. The concept was interesting, the performance was terrible, and businesses mostly didn't want to touch it. After I setup clients with a generic set of rules that worked on Prolog facts, most all of my clients were happy to limit their changes to only those fact files.
  • A few years ago I wrote a workforce scheduling program designed to be used by non-programmers. I worked in a restricted environment so couldn't install anything. The whole thing ran on SWIPL's web offering.

    Users simply had to change the basic "facts" (who was available on what days, how many people were needed), and the program solved for the various constraints and offered solutions.

    It was maybe about 300 lines of Prolog, no complex dependencies. It replaced a pile of Python scripts that required a lot of state, didn't really work, and could only run on a few specific computers.

    For regular users, it was relatively easy to understand and change the facts. SWIPL for web also offers a nice "notebook" interface that lets you mix data, code, and markdown / output blocks so the documentation was inline.