Prolog recursivly build list based on dot product -
hi have prolog function/predicate? takes dot product of 2 list. , use write function builds list of dot products list , list of list. basically, dot product called on each list in list of list function dot below , works.
dot([], [], 0). dot([head|tail], [head2|tail2], result) :- prod = head * head2, dot(tail, tail2, remaining), result prod + remaining.
this attempt @ function fails every-time try run it. can 1 help?
dotall([], [[]], [0]). dotall(x, [[head]|[tail]], result) :- dotunit(x, head, prod), result = [prod|result], dotall(x, tail, result).
to sum of goal, if passed in dotall([1,2,3],[[1,2,3],[4,5,6],[1,2,3]], what).
back, what
[15,32,15]
.
i know mouth full hope 1 can give me pointers on im going wrong. im new prolog.
the dotall
predicate believe (from example) defined be:
dotall(vector, listofvectors, results)
and says results
list of dot product results obtained taking dot product of vector
each vector in listofvectors
.
reviewing dotall
predicate:
dotall(x, [head|tail], [prod|result]) :- % dotall of x [head|tail] % [prod|result] if... dot(x, head, prod), % prod dot product of x w/head %result = [prod|result], % fail dotall(x, tail, result). % , result list of % dot products of x tail
notes recursive case:
- the
result = [prod|result]
fail since saying, i haveresult
, it's same thing[prod|result]
cannot true. - you can use third argument in clause, shown, express result list in recursive case (
[prod|result]
)
then base case:
dotall(_, [], []). % dot product of % empty list of vectors empty
notes base case:
- the first argument not
[]
because recursive predicate doesn't reduce first argument down empty list. first argument vector started used dot product elements in vector list (second argument). since don't care vector in base case, use_
. - the second argument
[]
, empty list since base case happens when we've exhausted list of vectors, list of lists. when end of lists of lists, have empty list ([]
). - the third argument empty list
[]
not[0]
because it's logical: if take dot product of vector empty vector list, should no results (an empty list[]
).
using above corrections:
| ?- dotall([1,2,3],[[1,2,3],[4,5,6],[7,8,9]], r). r = [14,32,50] ? ; no
Comments
Post a Comment