If I have a list in Prolog, made up of operators and operands, how do you interpret the list to achieve the appropriate operators on the appropriate operands?
So lets say we have a list of
[100, 25, sum, 2, multiply, 800, 50, subtract, sum]
should result in [1000]
by the following steps
// 100 and 25 are summed together, making it
[125, 2, multiply, 800, 50, subtract, sum]
// 125 and 2 are multiplied, making it 250
[250, 800, 50, subtract, sum]
// 50 is subtracted from 800, making it 750
[250, 750, sum]
// 250 is added to 750, making it 1000
[1000]
I am trying to understand the structure of how to make this happen (in particular, how to iterate through the list and make appropriate actions, not so much on the helper predicates that do the actual work[sum, multiple, etc]). Which scenario is best, and what other considerations should I consider?
Scenario 1 'Along the way' (main predicate, which has list1(before evaluation), and list2 (the final list) ):
- Look for the first instance of a non integer in list1
- Check to see if that 'word' is in a dictionary or list (probably using
member
), and if it is, see if there are enough preceding values in the list to accomplish it, if so, return the completed operation with the tail, if not, return false. - Continue until no more words are found
Scenario 2 'Look ahead' (main predicate, which has list1(before evaluation), and list2 (the final list) ):
- Look at each element in the list, keeping track of the maximum number of numbers required for the longest operator (lets say and operation called
duplicatePairs
needed two sets of pairs, therefore 4 numbers) - If I come across an operator, perform the operation, and return the unused head (if any) with the completed result and the tail.
- Continue until no more words are found
Scenario 3 'Fold Left' (main predicate, which has list1(before evaluation), and list2 (the final list) ):
- Using some map function (maplist/3 maybe), somehow recursively left fold through the list1 until the final list is achieved (borrowing this idea from functional programming[Haskell])