0

I am new to prolog. I was asked this question. I cannot be done in SWI-Prolog. Just in prolog base (not sure what to call it). All the answers I found were in SWI-Prolog.

First element of each nested list is either a 0 or a 1. The second element of each nested list is some integer.

As an example: [[0 1] [1 2] [1 3] [0 4] [0 3]]

First element of each nested list is the key and the second element of the nested lists is the value.

In prolog, implement a predicate, count by cat/2, that takes such a list as input and yields a two element list where:

  • the first element is the sum of the values of all nested lists with 0 as the key, and
  • the second element is the sum of the values of all nested lists with 1 as the key.
DuDa
  • 3,718
  • 4
  • 16
  • 36

1 Answers1

0

I assume that without swipl you mean with standard prolog. I used gnu prolog v1.5.0 to check my answer which follows the standard.

You start first by your base case a 0 for summation. then you check each condition. for 0 you add to Sum_0 and for 1 you add to Sum_1. and that hold for the rest of the list Tail .

cat([],[0,0]). 

cat([[0,Value]|Tail],[Sum_0,Sum_1]):-
    Sum_0 is Value + Sum0,
    cat(Tail,[Sum0,Sum_1]).

cat([[1,Value]|Tail],[Sum_0,Sum_1]):-
    Sum_1 is Value + Sum1,
    cat(Tail,[Sum_0,Sum1]).

Note: you can use #= instead of is to make the predicate more pure, you will need to add :- use_module(library(clpfd)). to import clpfd.

mikel
  • 1,043
  • 9
  • 4