1

I would like to count how often element x is in list L.

I know there is a way with recursion, but is it also possible like this:

> count(X,L,C) = C is (length(L,Length) - length(delete(L, X,
> List2),Length)).
?

The compiler say no:) What could I change?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
katarina
  • 33
  • 3

1 Answers1

1

No, since length(L, Length) is not a function. It is a predicate, so it is True or False (or gets stuck in an infinite loop, or errors, but you can argue that these are not really "results" of a predicate).

Furthermore, you can not call a predicate like length(delete(L, X, List2), Length), since, for the Prolog interpreter, the delete/3 is here just a functor. It will thus not call the delete/3 predicate.

You can however rewrite this to:

count(X, L, C) :-
    length(L, N1),
    delete(L, X, L2),
    length(L2, N2),
    C is N1 - N2.
Ch3steR
  • 20,090
  • 4
  • 28
  • 58
Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
  • @katarina: Note that `X = b, count(X,[a,a],0).` correctly succeeds, yet, `count(X,[a,a],0), X = b.` fails. Thus, this definition is not a relation. A definition that succeeds for both is [here](https://stackoverflow.com/a/44377914/772868). – false Mar 01 '20 at 14:05