r/programming • u/svpino • May 08 '15
Five programming problems every Software Engineer should be able to solve in less than 1 hour
https://blog.svpino.com/2015/05/07/five-programming-problems-every-software-engineer-should-be-able-to-solve-in-less-than-1-hour
2.5k
Upvotes
7
u/maskull May 08 '15 edited May 08 '15
Not the poster, but since I just finished my MS thesis in Prolog, I'll take a stab. :)
Preface: Prolog programs consist of predicates, things that are asserted to be true. E.g.,
is a zero-argument predicate that is always true.
means "p is true if q is true". In terms of evaluation, this is taken as "to prove p, prove q".
means "to prove p, prove q and then prove r".
Predicates don't return values like functions, they express truth, which means that Prolog can be somewhat flexible with which arguments to a predicate are "inputs" and which are "outputs".
Predicates in Prolog that take different numbers of arguments but have the same name are considered different. Here we're just defining an easy-to-call version of
sumthat takes three arguments (list of values as input, the signs to attach to each element, and the final sum, as outputs). The only thing it does is split the input list into its head and tail.This is the base case of the recursion. If the list of inputs contains a single value X, then no sign is attached to X (the list of signs is empty) and the sum is just X.
Here we try adding the first and second elements of the list together. This works recursively by replacing the head of the list with the First + Second (and adding a + to the list of signs, to keep track of what we did).
Here we try subtracting the second argument from the first. Again, recursive, replace the head of the input list and add '-' to the list of signs.
Here we try concatenating two digits from the list, so [1, 0] becomes [10]. Again, we replace the head of the list with the new value and recurse.
Here's the results running this on the list [1,2,3]:
But note that I can run this with all three arguments bound to check a particular answer:
I can even run it with the Signs unbound and Prolog will figure out what it should be
Or with Result unbound, to compute an answer for some particular list of inputs and signs:
We can't run it with the input argument unbound, because the
ispredicate expects its arguments to be bound. (With constraint logic we could.)