Write simple Prolog functions such as the following. Take into account lists which are too short. -- remove the Nth item from the list. -- insert as the Nth item.
๐ป Solution
week9.pl/* Description:
Write simple Prolog functions (predicates) on lists:
1) remove_nth(N, List, NewList) - removes the Nth item of List.
2) insert_nth(Item, N, List, NewList) - inserts Item as the Nth item of List.
Lists which are too short are taken into account:
-- if List has fewer than N items, remove_nth leaves the list unchanged.
-- if List has fewer than N-1 items, insert_nth adds the item at the end of the list.
*/
/* Production rules:
remove_nth(N, [], []) if the list is empty (too short)
remove_nth(1, [_|T], T) the first item is removed
remove_nth(N, [H|T], [H|R]) keep H and remove the (N-1)th item of T
insert_nth(X, N, [], [X]) if the list is empty (too short), X is added
insert_nth(X, 1, L, [X|L]) X becomes the first item
insert_nth(X, N, [H|T], [H|R]) keep H and insert X as the (N-1)th item of T
*/
% Clauses:
remove_nth(_, [], []) :- !.
remove_nth(1, [_|T], T) :- !.
remove_nth(N, [H|T], [H|R]) :-
N > 1,
N1 is N - 1,
remove_nth(N1, T, R).
insert_nth(X, _, [], [X]) :- !.
insert_nth(X, 1, L, [X|L]) :- !.
insert_nth(X, N, [H|T], [H|R]) :-
N > 1,
N1 is N - 1,
insert_nth(X, N1, T, R).
๐ค Output
w9.txt% Queries:
?- remove_nth(3, [a,b,c,d,e], R).
R = [a, b, d, e].
?- remove_nth(1, [a,b,c], R).
R = [b, c].
?- remove_nth(5, [a,b,c,d,e], R).
R = [a, b, c, d].
?- remove_nth(7, [a,b,c], R).
R = [a, b, c].
?- insert_nth(x, 3, [a,b,c,d], R).
R = [a, b, x, c, d].
?- insert_nth(x, 1, [a,b,c], R).
R = [x, a, b, c].
?- insert_nth(x, 4, [a,b,c], R).
R = [a, b, c, x].
?- insert_nth(x, 9, [a,b,c], R).
R = [a, b, c, x].
?- insert_nth(x, 1, [], R).
R = [x].