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.
Related
The idea is as follows: Suppose I have a list P = [(1,0),(4,3)] or similar. I want to evaluate the polynomial that's defined by this list in the manner: 1X^0 + 4X^3.
To do this, I've written the following:
evaluate(P,X,Y) :- evaluate(P,X,Y,0).
evaluate([],_,S,S).
evaluate([P1,P2|Ps],X,Y,S) :-
S1 is S+P1*X^P2,
evaluate(Ps,X,Y,S1).
Which is supposed to succeed when Y is the sum of the polynomial P, given x=X.
The problem is that when I try and run this code, I get the error:
is/2: Arithmetic: `(',')/2' is not a function
But I have no idea where this is coming from or how to fix it.
I did try splitting the S1 is up in to its segments, but doing that didn't help.
EDIT: Ok, I found out that it's about the way the list is written down. How do I work with tuples in this way within the bounds of Prolog?
Your problem is that your data structure for each item in the list is a tuple as you noted and where you access the values of tuple in the list is not correct.
This
evaluate([P1,P2|Ps],X,Y,S) :-
should be
evaluate([(P1,P2)|Ps],X,Y,S) :-
Notice the parenthesis around P1,P2.
When I run with the change I get
?- evaluate([(1,0),(4,3)],5,Y).
Y = 501.
Also it is common to put the output arguments at the end,
evaluate_01(P,X,Y,0).
as
evaluate_01(P,X,0,Y).
and then change the other predicates as necessary.
evaluate_02(P,X,Y) :- evaluate_02(P,X,0,Y).
evaluate_02([],_,S,S).
evaluate_02([(P1,P2)|Ps],X,S,Y) :-
S1 is S+P1*X^P2,
evaluate_02(Ps,X,S1,Y).
As an interesting option, this can be done with maplist/3 and sumlist/2:
evaluate_poly(Poly, X, R) :-
maplist(evaluate_term(X), Poly, EvaluatedTerms),
sumlist(EvaluatedTerms, R).
evaluate_term(X, (Coeff, Power), TermValue) :-
TermValue is Coeff * (X ^ Power).
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
I am learning OCaml. I know that OCaml provides us with both imperative style of programming and functional programming.
I came across this code as part of my course to compute the n'th Fibonacci number in OCaml
let memoise f =
let table = ref []
in
let rec find tab n =
match tab with
| [] ->
let v = (f n)
in
table := (n, v) :: !table;
v
| (n', v) :: t ->
if n' = n then v else (find t n)
in
fun n -> find !table n
let fibonacci2 = memoise fibonacci1
Where the function fibonacci1 is implemented in the standard way as follows:
let rec fibonacci1 n =
match n with
| 0 | 1 -> 1
| _ -> (fibonacci1 (n - 1)) + (fibonacci1 (n - 2))
Now my question is that how are we achieving memoisation in fibonacci2. table has been defined inside the function fibonacci2 and thus, my logic dictates that after the function finishes computation, the list table should get lost and after each call the table will get built again and again.
I ran some a simple test where I called the function fibonacci 35 twice in the OCaml REPL and the second function call returned the answer significantly faster than the first call to the function (contrary to my expectations).
I though that this might be possible if declaring a variable using ref gives it a global scope by default.
So I tried this
let f y = let x = ref 5 in y;;
print_int !x;;
But this gave me an error saying that the value of x is unbounded.
Why does this behave this way?
The function memoise returns a value, call it f. (f happens to be a function). Part of that value is the table. Every time you call memoise you're going to get a different value (with a different table).
In the example, the returned value f is given the name fibonacci2. So, the thing named fibonacci2 has a table inside it that can be used by the function f.
There is no global scope by default, that would be a huge mess. At any rate, this is a question of lifetime not of scope. Lifetimes in OCaml last as long as an object can be reached somehow. In the case of the table, it can be reached through the returned function, and hence it lasts as long as the function does.
In your second example you are testing the scope (not the lifetime) of x, and indeed the scope of x is restricted to the subexpresssion of its let. (I.e., it is meaningful only in the expression y, where it's not used.) In the original code, all the uses of table are within its let, hence there's no problem.
Although references are a little tricky, the underlying semantics of OCaml come from lambda calculus, and are extremely clean. That's why it's such a delight to code in OCaml (IMHO).
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.
I am a complete beginner to J. My first attempt at writing a function is something like the totient function. It takes an array, assumed to be i.num for some number, num. And then computes the number of elements coprime to the tally of the array.
If I do it manually like this:
numbers =: i.7
#(1=( #numbers)+./numbers)#numbers
it works. The result is 6.
So I want to turn this into a general function.
Tot =: monad :'(1=( #x)+./x)#x'
Tot i.11
This fails and I get a value error for x. I don't know why.
The monad's variable should be y, not x:
Tot =: monad :'(1=( #y)+./y)#y'
x is the left argument of a dyad.