I want to write a code in prolog that gets a list and find its positive numbers and adds them into a new list as below :

```
?- findPositives([-1,2,3,-5,-7,9],Result)
Result : [2,3,9]
```

How can I write this code?

Tag: prolog

I want to write a code in prolog that gets a list and find its positive numbers and adds them into a new list as below :

```
?- findPositives([-1,2,3,-5,-7,9],Result)
Result : [2,3,9]
```

How can I write this code?

Using `tfilter/3`

:

```
positive_truth(N, true) :-
N >= 0.
positive_truth(N, false) :-
N < 0.
?- tfilter(positive_truth, [-1,2,3,-5,-7,9],Result).
Result = [2,3,9]
```

Alternatively, using `library(clpfd)`

:

```
pos_truth(Expr, Truth) :-
Expr #>= 0 #<==> Bool,
bool01_truth(Bool, Truth).
bool01_truth(0,false).
bool01_truth(1,true).
?- tfilter(pos_truth, [-1,2,3,-5,-7,9],Result).
Result = [2,3,9].
?- tfilter(pos_truth, [X,Y],Result).
Result = [], X in inf.. -1, Y in inf.. -1
; Result = [Y], X in inf.. -1, Y in 0..sup
; Result = [X], X in 0..sup, Y in inf.. -1
; Result = [X, Y], X in 0..sup, Y in 0..sup.
```

It doesn't work all at once, but bit by bit. As if defined by the following two clauses: repeat. repeat :- repeat. ...

You want to describe a sequence of elements. For such, there is a special formalism in Prolog called Definite Clause Grammars. Before using the formalism, let's try to figure out how a sequence with E occurring exactly twice looks like: First, is a possibly empty sequence which does not contain...

algorithm,prolog,unification,iso-prolog

Third attempt. This is mainly a bugfix in a previous answer (which already had many modifications). Edit: 06/04/2015 When creating a more general term I was leaving both subterms as-is if either of them was a variable. Now I build a more general term for the "other" subterm in this...

If you do experiments as a beginner, better stick to using the prolog-toplevel. In this manner you can rapidily identify the problem. Since you are most probably using SWI7 - like so: ?- append("hello ", B, FinalString), append(A, "world", FinalString), append(A, B, FinalString). false. So if this is false, lets...

Use is/2 to force the arithmetic evaluation. On their own, Prolog terms are just structural symbolic entities, X-2 is a compound term of arity 2, -(X,2): 3 ?- write_canonical( X-2 ). -(_,2) true. But is is for arithmetic expressions: 4 ?- Z is 5-2. Z = 3. Your definition should...

Your list is for all intents and purposes a base-100 number. The easy way to solve it is to do the arithmetic in the same way in which you would evaluate it long hand: start with the least significant digit, working to the most significant digit, sum each pair of...

oauth,google-api,prolog,swi-prolog

Okay finally worked this step out. If anyone is interested: Using status_code(_ErrorCode) seemed to resolve the problem with streampair and I needed to set redirect_uri='postmessage' for the request to work. I also used http_open rather than http_post. :- use_module(library(http/thread_httpd)). :- use_module(library(http/http_dispatch)). :- use_module(library(http/http_error)). :- use_module(library(http/html_write)). :- use_module(library(http/http_session)). :- use_module(library(http/js_write)). :-...

@gusbro's answer (s(X)) shows you how you somewhat solve this with GNU's debugger. However, if you cannot afford to see all the printing going on, or it is much too slow, you might consider the following "debugger". I personally do not use debuggers offered by Prolog systems for the simple...

You keep track of what nodes in your graph that you've already visited. You need to do this anyway, as you need to detect cycles in your graph lest you fall into the rabbit hole of infinite recursion. And in Prolog, we use helper methods that carry state around as...

Use unification: ?- List = [a=3, b=2, c=0], member(Left=Right, List). List = [a=3, b=2, c=0], Left = a, Right = 3 ; List = [a=3, b=2, c=0], Left = b, Right = 2 ; List = [a=3, b=2, c=0], Left = c, Right = 0. Here, something like a=3 is...

module,prolog,standards,iso,iso-prolog

The system you cite, SWI-Prolog, is a system whose core is developed by a single developer. Such bold statements as those you quote are his very personal opinions. In the past, SWI did follow ISO standards for a certain period. Then, recently changed. If you want to read more about...

You asked: So how can I solve this? The following is a general methodology, that always works for pure, monotonic Prolog programs like yours. Your actual problem is that a specific goal should succeed, but it fails. So you got an unexpected failure. To localize the responsible part of your...

You can use findall followed by sort to collect unique results of a query (you don't want duplicate invoices in your list), and length to check the length of the collected results. For example: findall(X, (invoice(X, C, P, _), customer(C, _, f, _), cleanProd(P)), Xs), sort(Xs, InvoicesOfWomenBuyingCleanProducts), length(InvoicesOfMenBuyingCleanProducts, N). Also,...

In Prolog, you cannot reassign variables. So expressions such as R is R // 2 will fail since, in Prolog, it semantically says that *R is itself integer divide by 2 which would only be true if R was 0. Likewise, given that a Tape is a list, you cannot...

prolog,artificial-intelligence,expert-system

It works, at least in SWI-Prolog version 6.6.6. Let's have both rules defined: rule((fix(Advice) :- (bad_component(X), fix(X, Advice))), 100). rule((fix(Advice) :- (bad_component(X); fix(X, Advice))), 100). If we ask for available rules we obtain both of them: ?- rule((A :- B), C). A = fix(_G2329), B = (bad_component(_G2334), fix(_G2334, _G2329)), C...

prolog,primes,sieve-of-eratosthenes,prolog-coroutining

Ok i found out solution i had to change recursive call in sieve so now i call it in freeze predicate. as requested i found clue here Lazy lists in Prolog? sieve(N,L) :- sieve(L,Strumien,[]), numlist(2,N,X), X = Strumien. sieve(L,Strumien,X) :- freeze(Strumien, ( Strumien =[H|T], filter(H,T,Z), sieve(L,Z,[H|X]) )). sieve(L,[],L). filter(H,S,X) :-...

Try: lemmas:- odbc_query('my_db', 'SELECT * ,case \ when ActualCost<EstimatedCost then \'true\' \ else \'false\' \ end as Value \ from Work_Order ' ). ...

You need an extra argument for the list. So you cannot call it check/1 having a single argument, but — let's say — related_to/2. related_to(X, Ys) :- setof(Y, fact(X, Y), Ys). Sample queries: ?- related_to(a, Xs). Xs = [b, d]. ?- related_to(b, Xs). Xs = [c]. ?- related_to(d, Xs). false....

You need to say prompt(_, '') somewhere in your program before you start reading and writing to standard streams. From the entry for prompt/2: A prompt is printed if one of the read predicates is called and the cursor is at the left margin. It is also printed whenever a...

The correct first clause of your predicate is a combination of the two clauses you have on top now. First one insists the K is 0: you don't want this. Second one insists on having one extra variable at the end of the second list: you don't want this either....

_ alone is an anonymous variable. Multiple occurrences in the same clause (or the same read-term) represent different variables. A variable starting with _ but containing further characters is not an anonymous variable. Several occurrences represent the same variable. By convention, many Prolog systems require that variables occurring only once...

It's possible there are other problems, but reverse([], ReversedList). is almost surely not what you want here. The reverse of an empty list is an empty list, translates to reverse([], []). Additionally, reverse([A,B], ReversedList) is also probably not what you want. It is not a list with head A and...

Solved using another approach. Code is attached (algorithm is in the code). Some predicates from prev. case remained though (like try_bind). Code at http://pastebin.com/0Eb7qUjS or: % Author: Denis Korekov % Description of algorithm: % G1 is graph 1, G2 is graph 2 % E1 is edge of G1, E2 is...

TL;DR: Prolog is right. And you really are doing the best taking the messages seriously. You are using if-then-else in an unconventional manner. For this reason it is not that simple to figure out what is happening. When I say listing(check) I get the following: check(A, B) :- ( related_to(A,...

In prolog there is no concept of functions like you are trying to do in your code. You should do: random(N), assert(fact(N)) I recommend reading at least first two chapters Learn Prolog Now! to better understand search and unification....

Generally, you do not iterate in Prolog. Instead, you write a rule with a pair of recursive clauses, like this: dosomething([]). dosomething([H|T]) :- process(H), dosomething(T). The first clause processes the base case, when the list [] is empty. In this case, there is nothing to do, so the body of...

Most likely you are looking for when/2. It is offered by both SICStus Prolog (manual page) and SWI-Prolog (manual page). Sample use: myfreeze1(V,Goal) :- when(nonvar(V),Goal). myfreeze2(V1,V2,Goal) :- when((nonvar(V1);nonvar(V2)),Goal). ...

string,split,prolog,swi-prolog,punctuation

"split_string" is not standard but, in the implementation I know, you can not. From the ECLIPSe manual: The string String is split at the separators, and any padding characters around the resulting sub-strings are removed. Neither the separators nor the padding characters occur in SubStrings. http://www.cs.uni-potsdam.de/wv/lehre/Material/Prolog/Eclipse-Doc/bips/kernel/stratom/split_string-4.html ** Addendum ** We...

write('\33\[1mbold\33\[0m'). That is, octal escape sequences (and hexadecimal which start with \x) need to be closed with a \ too. En revanche, a leading zero is not required, but possible. This is in no way specific to GNU, in fact, probably all systems close to ISO Prolog have it....

Prolog is a declarative language, you must state correctly your patterns: size(node(L,R), Size) :- ... % why you add 1 to left+right sizes ? From the samples, I suggest to stop the recursion with Size = 1 when anything that is not a node is seen: size(node(L,R), Size) :- !,...

The cut in above examples has the following effect: Ideally, it commits the search which might happen within solve_task_a/6 to the first answer found. This frees resources for finding further answers which improves space consumption. Scope problems However, at the same time, it might also hide further answers to agent_current_position/2....

maplist(P_1, Xs) will call call(P_1, X) for each element of Xs. The built-in predicate call/2 adds one further argument to P_1 and then calls this with call/1. To indicate that a further argument is needed, it is very helpful to use a name like P_1 meaning "one extra argument is...

Determinstic variant First a more efficient but deterministic approach: occurs_most([],_,0). occurs_most(List,X,Nr) :- msort(List,[H|T]), most_sort(T,H,1,H,1,X,Nr). most_sort([Hb|T],Ha,Na,Hb,Nb,Hr,Nr) :- !, Nb1 is Nb+1, most_sort(T,Ha,Na,Hb,Nb1,Hr,Nr). most_sort([Hc|T],_,Na,Hb,Nb,Hr,Nr) :- Nb > Na, !, most_sort(T,Hb,Nb,Hc,1,Hr,Nr). most_sort([Hc|T],Ha,Na,_,_,Hr,Nr) :- most_sort(T,Ha,Na,Hc,1,Hr,Nr). most_sort([],Ha,Na,_,Nb,Ha,Na) :- Na >= Nb, !. most_sort([],_,_,Hb,Nb,Hb,Nb). First you use msort/2 to sort the list. Then you iterate over...

maybe, using another casual predicate instead of main/0... ?- with_output_to(atom(X), listing(pattern)), write(X). gram:pattern(A, B, C) :- dig(A, B, C). gram:pattern(A+C, B, E) :- ten(A, B, D), dig(C, D, E). ... ...

Near to correct, but some small error. Line by line: a) spit([], 0, [], []). typo: spi vs split The rule says "the split of an empty list by 0 are two empty lists", true, but too restrictive, change it to "the split of empty list is two empty list,...

As I understand it, you want a predicate that evaluates this function: In a procedural language, you'd write something like this iterative solution: static double iterative_harmonic_number( int n ) { if ( n < 1 ) throw new ArgumentOutOfRangeException("n"); double r = 0.0 ; while ( n > 0 )...

Yes, of course, there is a solution. You are getting a list of results so you need to filter them by specific predicate or just take last one because you sort them in increasing order. Prolog generates these solutions one by one. Sometimes we would like to have all the...

OK, this is a complex issue. You assume it is a trick question, but is it really one? How can we be sure? I will let library(clpfd) do the thinking for me. First I will rewrite your program: :- use_module(library(clpfd)). fx([],0). fx([H|T],S):- fx(T,S1), S1 #> 2, S #= S1 +...

My Prolog is slightly rusty, but I believe that this should do it: node(Left, Right). trav(node(Left, Right), L) :- trav(Left, L1), trav(Right, L2), append(L1, L2, L). trav(X, [X]) :- X \= node(A, B). Intuitively, trav(Left, L1) says traverse the left subtree, storing each element in L1. trav(Right, L2) says traverse...

Using tfilter/3: positive_truth(N, true) :- N >= 0. positive_truth(N, false) :- N < 0. ?- tfilter(positive_truth, [-1,2,3,-5,-7,9],Result). Result = [2,3,9] Alternatively, using library(clpfd): pos_truth(Expr, Truth) :- Expr #>= 0 #<==> Bool, bool01_truth(Bool, Truth). bool01_truth(0,false). bool01_truth(1,true). ?- tfilter(pos_truth, [-1,2,3,-5,-7,9],Result). Result = [2,3,9]. ?- tfilter(pos_truth, [X,Y],Result). Result = [], X in inf.....

You need to use the vertical bar [Top|Rest] syntax twice in order to pull out an element from the nested list, like this: testfunction([[Top|_]|_]):- write(Top),nl,nl. Now Top unifies with the first element of the first list in a list of lists. Note that you do not have to use unification...

The Zebra puzzle, a.k.a. Einstein's Riddle, is a logic puzzle which is to be solved programmatically. It has several variants, all in the form of the one you posted. SPOILER ALERT: the following links contain prolog solutions to the puzzle Here is a solution using ic (constraint solver) library: https://gist.github.com/JuanitoFatas/2227711...

Seems fine to me... What's the problem? $ swipl Welcome to SWI-Prolog (Multi-threaded, 64 bits, Version 7.1.37) Copyright (c) 1990-2015 University of Amsterdam, VU Amsterdam SWI-Prolog comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions. Please visit http://www.swi-prolog.org for details....

If L is a term, you can replace: %append(L,List,List_New), with: List_New=[L|List], ...

The error is very likely because in your code: listtrans([H|T],L1):- trans(H,B), append(B,L,L2), listtrans(T,L2). the variable L1 is declared in the head, but not referenced anywhere: you mispelled something? Anyway, your code is not going to work. Moreover, using append/3 for this kind of tasks which are easily defined by recursion...

It is a non-provable operator. See this link to learn more. Basically, it's true if the argument is not provable.

bash,prolog,swi-prolog,logic-programming

I think this has nothing/not much to do with SWI-prolog itself, but more with the command line handler. If I place the goal between single quotes (''), it works: swipl -s consultingfile.pl -g 'start(1)' The brackets are probably wrongly interpreted by the shell. If I use your command it gives:...

The answer by CapelliC is perfect. Just to explain: When you have a Prolog clause like this: foo([H|T], [H|Z]) :- foo(T, Z). which you then call like this: ?- foo([a,b,c], L). from: foo([H| T ], [H|Z]) with H = a, T = [b,c], L = [a|Z] call: foo([a|[b,c]], [a|Z]) which...

+1 for using CLP(FD) constraints for this task! forall/2 and constraints do not mix very well, since backtracking revokes posted constraints. Your example works as expected with: flip_init(Prop, D) :- clpfd:init_propagator(D, Prop). and using maplist(flip_init(Prop), Ds) instead of forall/2. The next problem is then that digits_to_nonneg([1,2], N) simply fails, but...

The article seems not be very explicative. Assume the call is "sg(a,W)". Let analize first possibility: sg(X,Y) :- par(X, X1), par(Y,Y1), sg(X1,Y1) first "par" will be queried as "par(X=a,X1)", next as "par(Y=W,Y1)". This last query is a totally unbound query, and probably is what the article tries to skip. Now,...