HOMEWORK 3.
1. Write a program for factorial computation using accumulator.
=================================================
2. Write a program sum_and_squaresum that from a given list of numbers
finds the sum of its elements and the sum of their squares. Use
accumulators. Sample run:
?- sum_and_squaresum([1,-3,2,0],Sum,SQS).
Sum = 0
SQS = 14 ;
No
=================================================
3. Define the relation flatten_list(InputList, FlatList) where
InputList can be a list with nested occurrences of lists, and
FlatList is InputList "flattened" so that the elements of
InputList's sublists (or sub-lists, sub-sub-lists, etc) are
reorganized as one plain list. Use difference structures.
A sample session should look something like:
?- flatten_list([1,[a,[b,c]],2,[d],[]],X).
X=[1,a,b,c,2,d];
No
?- flatten_list([[]],X).
X=[];
No
?- flatten_list([1,[a,[b,c]],2,[d],[]],[1, a, b, c, 2, d]).
Yes
?- flatten_list([1,2], X).
X = [1, 2] ;
No
Make sure that the program does not return multiple solutions. For
instance, you should NOT get something like:
?- flatten_list([1,[a,[b,c]],2,[d],[]],X).
X = [1, a, b, c, 2, d] ;
X = [1, a, b, c, 2, d, []] ;
X = [1, a, b, c, 2, d, []] ;
X = [1, a, b, c, 2, d, [], []] ;
X = [1, a, b, c, 2, d, [[]]]
...
You can use 'cut' to prevent such cases.
========================================================
4. Write a predicate twice_as_long(L1,L2) that succeeds
if the list L2 is twice as long as the list L1. Do NOT
compute the lengths of the lists. Sample run:
?- twice_as_long([],[]).
Yes.
?- twice_as_long([a],[1,2]).
Yes.
?- twice_as_long([a,b],X).
X = [_G328, _G331, _G334, _G337] ;
No
?- twice_as_long(X,[_,_]).
X = [_G328] ;
No
?- twice_as_long([_],X).
X = [_G313, _G316] ;
No
========================================================