swi-prolog strange recursion write - recursion

I have a similar recursion function:
fillTable(X0,Y0,Yn,Yh):-
checkPoint(X0,Y0),
Ynext = Y0+Yh,
Ynext=<Yn,
fillTable(X0,Ynext,Yn,Yh).
checkPoint(X,Y):-
(-X-1)<Y,
X<0, Y<0,
write(X), writeq(' '), write(Y),write(' in 1 area'),
nl,
!
;
(-X+1)>Y, X>0, Y>0,
write(X),write(' '), write(Y),write(' in 2 area'),
nl,
!
;
write(X),write(' '),write(Y),write(' not in area'),nl.
Where X, Y and other var's are float, but when it's written by write(), it prints -1+0.2+0.2+0.2+... not -0.8, -0.6 or other.
How can I fix it?

This is a common beginner's issue in Prolog to confuse "unification" with "assignment".
Your expression:
Ynext = Y0+Yh,
Does not assign the value of Y0+Yh to the variable Ynext. The predicate =/2 is the unification predicate, which will take the expressions on both sides and unify them. These expressions are Ynext, a variable, and Y0+Yh, which is the functor +/2 applied to two other variables (which in your case, are instantiated). In other words, it unifies Ynext with +(Y0,Yh) and does not evaluate it.
Let's suppose then you have Y0 instantiated as -1 and Yh as 0.2. Then, the unification expression above will be:
Ynext = -1+0.2,
Which will result in Ynext having the value -1+0.2 (which is, in prolog, the same as +(-1,0.2).
If you want to evaluate the arithmetic expression and assign it, you'd use is/2:
Ynext is Y0 + Yh,
Note that the inequalities </2, >/2, etc do evaluate. So the expression:
(-X+1)>Y
Will do what you expect it to, which is to succeed or fail depending upon whether the value of the arithmetic expression (-X+1) is less than the value of Y or not.

Related

Is either use of the equals sign '=' in R a symmetric relation?

I am aware of at least two distinct uses of the equals sign in the R-programming language:
(1) as a deprecated assignment operator, i.e. x = 3 instead of x <- 3.
(2) for passing values of arguments to functions, e.g. ggplot(df, aes(x = length, y = width))
Do either of these operators correspond to symmetric relations (in the sense of mathematics)?
The 'equals' operator == does (I think), which is why it corresponds most closely to the use of the equals sign in mathematics (which is always a symmetric relation).
But for example if one tried to run ggplot(df, aes(length = x, width = y) one would get an error, and one would also get an error trying to run 3 = x.
Thus, is it true that, unlike in mathematics, the equals sign in R is not a symmetric relation? Is that why <- is preferred by some for assignment, because it better conveys the lack of symmetry?
Bonus question: are there other programming languages where the equals sign does not correspond to a symmetric relation? PowerShell (I have never heard of it before) might be one.
The = operator is not symmetric in R. When it comes to assignment, = is basically a function that takes a symbol and a value and assigns that value to that symbol. When it comes to named parameters, it's really just part of the syntax of naming a parameter.
<- is preferred for assignment simply because it has an unambiguous meaning.

prolog factorial recursion giving expression as output

I've written a prlog recursive factorial clause which is:
factorial(X,Y):-
(X>1)
-> factorial(X-1,X*Y)
; write(Y).
The problem is, for any valid call[for example, factorial(5,1). ], it is giving an expression rather than a value[(5-1-1-1)* ((5-1-1)* ((5-1)* (5*1)))]. How can I get a value rather than an expression.
The comment by #lurker is a bit simplistic. Comparison operators do evaluate expressions. So, your code could be made to work:
factorial(X,Y):- X>1 -> factorial(X-1,F), Y=X*F ; Y=1.
?- factorial(5,X),F is X.
X = 5*((5-1)*((5-1-1)*((5-1-1-1)*1))),
F = 120.

Accessing values in expression using a macro

I'm wondering whether it's possible to define a macro that can modify the values of an expression only if the values are of a specific type?
Here's a minimal example:
type Special
x::Int
end
f1(s, n::Special) = println("f1", s, n)
f2(s, n::Special) = println("f2", s, n)
x1 = Special(3)
x2 = Special(5)
expr = :(
f1("this is f1", x1),
f2("this is f2", x2)
)
Now a macro might be able to examine the values of the arguments to the functions, determine that x1 and x2 are of type Special, run some function to modify their values, say by changing 3 to 4 and 5 to 2 (it might involve comparing two values), then pass the expression back to the caller. The final result would be equivalent to calling:
f1("this is f1", 4)
f2("this is f2", 2)
I found that it's possible to access the values in a macro via:
eval(eval(filter(x -> typeof(eval(x)) == Special, expr.args[1].args))[1]).x
=> 3
but although this works it looks wrong, and I'm might either be doing it wrong or trying to do something too way out...
No, you should never try to check types or values inside macros. Using eval to figure out the type or value of something in a macro may work in very limited situations, but it'll break in almost every real use. Instead, just have the macro insert a call to a generic function — that's where Julia excels at picking apart types (as method dispatch) and values (within the method):
munge_special(x::Special) = Special(x.x + 42)
munge_special(x) = x
macro do_something_special(x)
return :(munge_special($(esc(x))))
end
julia> #do_something_special Special(2)
Special(44)
julia> #do_something_special 3
3

Does Julia have a ternary conditional operator?

Python, Java and Scala have ternary operators. What is the equivalent in Julia?
You may be referring to this.
a = true
b = 1
c = 2
julia>a ? b : c
1
a = false
julia>a ? b : c
2
For inline use, a ? b : c exists, as mentioned by the previous answer. However it is worth noting that if-else-end in Julia works just like (if cond expr1 expr2) in most Lisp dialects which acts both as the if-clause and as the ternary operator. As such, if-then-else returns the return value of the expression that gets executed.
Meaning that you can write things like
function abs(x)
if x > 0
x
else
-x
end
end
and this will return what you want. You do not have to use a return statement to break the function block, you just return the value returned by the if-block.
Inline, you can write
if (x > 0) x else -x end
which will return the same thing as the ternary operator expression (x > 0) ? x : -x , but has the benefit of avoiding perl-ish ?: symbols and is generally more readable, but less chainable.
Most languages have a ternary operator separate from if-then-else because if clauses are statements, while in lisp-like languages they are expressions just like everything else and have a return value.
Yes! Julia has a ternary operator. Here is a quick example from the Julia documentation:
The so-called "ternary operator", ?:, is closely related to the if-elseif-else syntax, but it is used where a conditional choice between single expression values is required, as opposed to conditional execution of longer blocks of code. It gets its name from being the only operator in most languages taking three operands:
a ? b : c
The expression a, before the ?, is a condition expression, and the ternary operation evaluates the expression b, before the :, if the condition a is true or the expression c, after the :, if it is false. Note that the spaces around ? and : are mandatory: an expression like a?b:c is not a valid ternary expression (but a newline is acceptable after both the ? and the :).
The easiest way to understand this behavior is to see an example. In the previous example, the println call is shared by all three branches: the only real choice is which literal string to print. This could be written more concisely using the ternary operator. For the sake of clarity, let's try a two-way version first:
julia> x = 1; y = 2;
julia> println(x < y ? "less than" : "not less than")
less than
julia> x = 1; y = 0;
julia> println(x < y ? "less than" : "not less than")
not less than

count the number of calls of a clause

I have a clause like following:
lock_open:-
conditional_combination(X),
equal(X,[8,6,5,3,6,9]),!,
print(X).
this clause succeed. But I want to know how many times conditional_combination() is called before equal(X,[8,6,5,3,6,9]) is become true. the program is to generate a permutation by following some rules. And I need to how many permutation is need to generate to get a particular value like 865369.
What you actually want is something slightly different: You want to count the number of answers (so far) of a goal.
The following predicate call_nth(Goal_0, Nth) succeeds like call(Goal_0) but has an additional argument which indicates that the answer found is the n-th answer. This definition is highly specific to SWI or YAP. Do not use things like nb_setarg/3 in your general programs, but use them for well encapsulated cases as this one. Even within
those two systems, the precise meaning of these constructs is not well defined for the general case. Here is a definition for SICStus. Update: use unsigned_64 in newer versions instead of unsigned_32.
call_nth(Goal_0, Nth) :-
nonvar(Nth),
!,
Nth \== 0,
\+arg(Nth,+ 1,2), % produces all expected errors
State = count(0,_), % note the extra argument which remains a variable
Goal_0,
arg(1, State, C1),
C2 is C1+1,
( Nth == C2
-> !
; nb_setarg(1, State, C2),
fail
).
call_nth(Goal_0, Nth) :-
State = count(0,_), % note the extra argument which remains a variable
Goal_0,
arg(1, State, C1),
C2 is C1+1,
nb_setarg(1, State, C2),
Nth = C2.
A more robust abstraction is provided by Eclipse:
call_nth(Goal_0, Nth) :-
shelf_create(counter(0), CounterRef),
call(Goal_0),
shelf_inc(CounterRef, 1),
shelf_get(CounterRef, 1, Nth).
?- call_nth(between(1,5,I),Nth).
I = Nth, Nth = 1
; I = Nth, Nth = 2
; I = Nth, Nth = 3
; I = Nth, Nth = 4
; I = Nth, Nth = 5.
So simply wrap it around:
lock_open :-
call_nth(conditional_combination(X), Nth),
X = [8,6,5,3,6,9],
!,
....
If you are using SWI prolog you can use nb_getval/2 and nb_setval/2 to achieve what you want:
lock_open:-
nb_setval(ctr, 0), % Initialize counter
conditional_combination(X),
nb_inc(ctr), % Increment Counter
equal(X,[8,6,5,3,6,9]),
% Here you can access counter value with nb_getval(ctr, Value)
!,
print(X).
nb_inc(Key):-
nb_getval(Key, Old),
succ(Old, New),
nb_setval(Key, New).
Other prologs have other means to do the same, look for global variables in your prolog implementation. In this snippet I used the term ctr to hold the current goal counter. You can use any term there that is not used in your program.
While working on a module "micro", I recently invented pivots. They are inspired by the thread / pipe pattern to pass around data. A pivot is a bounded queue of maximum length one, the pivot_put/1 does a copy of the given term as well. But for performance reasons they don't use a synchronized and are non-blocking.
In as far they are very similar to nb_setarg/3, except that they don't destruct a Prolog term, but instead they update a Java data structure. As a result they are little bit safer than the non-logical term operations. Also they don't need some call_cleanup/3, since they are Java garbage collected.
In as far they are more similar than nb_setarg/3, than using some explicit allocate and dealloccate of structures. So for example a solution for SICStus Prolog could be:
call_nth(Goal_0, Nth) :-
new(unsigned_32, Counter),
call_cleanup(call_nth1(Goal_0, Counter, Nth),
dispose(Counter)).
call_nth1(Goal_0, Counter, Nth) :-
call(Goal_0),
get_contents(Counter, contents, Count0),
Count1 is Count0+1,
put_contents(Counter, contents, Count1),
Nth = Count1.
With pivots, there is even no 32-bit limitation, and we can directly do:
call_nth(G, C) :-
pivot_new(P),
pivot_put(P, 0),
call(G),
pivot_take(P, M),
N is M+1,
pivot_put(P, N),
C = N.

Resources