anyone have idea how to solve this problem
counts the number of occurrences of an operator inside an expression. For instance, the query:
?- count(a+b*c-(2开发者_JAVA百科+3*4)/(5*(2+a)+(b+c)^f((d-e)*(x-y))), *, C).
would count the number of occurrences of operator * in the expression given as the first argument and output on C
I am using SWI-prolog
Is this homework?
Here's some hints:
Prolog operators are syntactic sugar around normal prolog terms. The expression
3 * 2 + 1
is parsed as the term'+'('*'(3,2),1)
.The built-in predicate
=..
decomposes a term into a list, the head of which is the functor and the tail of which comprises the [non-decomposed] terms that are the arguments to the original term.The built-in predicate
functor/3
unifies a term with its functor and arity.You might also want to look at
arg/3
which provide the means to examine the arguments of the specified term by ordinal position.
Now that you know that, a fairly simple recursive solution should present itself. If you need to factor in the arity of the desired operator, it's a little more convoluted (but not much).
精彩评论