katarina
katarina

Reputation: 33

How to combine list operations?

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?

Upvotes: 1

Views: 48

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476544

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.

Upvotes: 1

Related Questions