Reputation: 9
I'm trying to do a predicate parlist(list,num,all).
"list" is basically a list of characters (for example ['a','b','c']), "num" is just a natural number, and "all" is the list that concatenate the list plus the number, except if the length of elements in the original list is 2 or more, then the output list "all" has to be between two parenthesis excluding the number.
Example for a list with length >=2:
parlist(['a','b','c'],3,R).
Output should be:
R=['(','a','b','c',')',3]
Example for a list with length <2:
parlist(['a'],2,R).
Output should be:
R=['a',2]
I'm a little bit lost with prolog, so i dont see how to start, please help. Thanks.
Upvotes: 0
Views: 70
Reputation: 74325
A lot of Prolog is pattern matching. You have three cases, right?
The empty list
Just make put the number in a list: [ 3 ]
Lists of length 1
Append the number to the list: [ a , 3 ]
Lists of length > 1
Enclose the list in parentheses and add the number at the end: [ '(', a, b, ')', 3 ]
.
For this you don't even need to iterate over the list. You just need to pattern-match in the head of your predicate clause.
Case 1: the empty list. This is easy:
parlist( [], N, [N] ).
Case 2: Lists of length 1. This is just as easy:
parlist( [X], N, [X,N] ).
Case 3: Lists of length > 1. A little more complex. You could use built-in here, or roll your own.
Builtins: We can use append/3
to effect here:
parlist( [X,Y|Zs], N, R ) :- append( ['(',X,Y|Zs], [')',N], R ).
Roll Your Own: You can roll your own almost as easily. We'll use a little specialized helper predicate here:
parlist( [X,Y|Zs], N, ['(' | R ] ) :- parlist1( ['(',X,Y|Zs], N, R ).
%--------------------------------------------------------------------
% If the list is of length >= 2, add the 1st two elements to the
% result list, and
% - recurse down on the tail.
%
% If the list is of length 0 or 1, we're done: close out the result with
% - the last element of the list (if present),
% - the lead-out parenthesis and
% - the number
%
%--------------------------------------------------------------------
parlist1( [X,Y|Zs] , N , [X,Y|R] ) :- parlist1( Zs , N , R ).
parlist1( [] , N , [ ')',N] ).
parlist1( [X] , N , [X,')',N] ).
Upvotes: 1