8
\$\begingroup\$

This meta-question is inspired by this challenge, which basically asks to count from 1 to N. However this is a question that bothers me in a lot of challenges which have those “iterative”/“print all X such that” kind of outputs.

So keeping as an example this challenge of counting from 1 to N, a possible solution in Prolog is to write a predicate which will unify a variable with an integer. Then, Prolog's backtracking mechanism makes it so that we can ask all possible values that make this predicate true.

For instance in this example, I could write a predicate a(N,I)which unifies I with an integer between 1 and N. Calling it would give this result:

?- a(5,I).
I = 1

However now instead of terminating, Prolog's REPL halts: if I type ; (logical or), it will give me a second answer:

I = 2

I can keep doing this until it finds no more solution:

I = 3 ;
I = 4 ;
I = 5

And now it has terminated.

Is this a fair way of returning/printing outputs? Note that it is possible to fill a list with all those unifications and return that list using findall, but this is obviously longer.

This question also applies for languages that work on Prolog (e.g. Brachylog) or that have a similar mechanism in their REPL (e.g. ?)

\$\endgroup\$
  • \$\begingroup\$ Seems kinda like a Python generator function, with consecutive calls, and the poilcy there is that the function should give in whole the required output [citation needed]. \$\endgroup\$ – cat Apr 26 '16 at 22:34
2
\$\begingroup\$

Yes, that is allowed.

It is almost the same as a list, in the sense that it doesn't output each term individually automatically.

Like cat pointed out, this is a lot like a python generator, which is an acceptable output format as far as I know.

\$\endgroup\$
  • \$\begingroup\$ No, Python generators are lazy magical black boxes -- to get all their output at once, you need [next(my_func()) for i in range(x)] or so \$\endgroup\$ – cat May 8 '16 at 23:18
  • \$\begingroup\$ @cat but I still think it is a valid output format? \$\endgroup\$ – Rɪᴋᴇʀ May 9 '16 at 1:13
  • \$\begingroup\$ Here's a source on allowing lists to be output as generators. I had Prolog in mind when I wrote it. Note that this isn't really connected with REPLs; you can do the same generator→list conversion from within code using findall. \$\endgroup\$ – user62131 Mar 27 '17 at 13:55

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .