Monday, July 17, 2023

5. Write a prolog program, insert_nth(item, n, into_list, result) that asserts that result is the list into_list with item inserted as the n‘th element into every list at all levels.

 5. Write a prolog program, insert_nth(item, n, into_list, result) that asserts that result is the list into_list with item inserted as the n‘th element into every list at all levels. 


insert_nth(Item,1,List,[Item|List]).

insert_nth(Item,Pos,[H|List],[H|Result]):-Pos1 is Pos-1,insert_nth(Item,Pos1,List,Result).





OUTPUT:

insert_nth(5,1,[2],X).
X = 2


insert_nth(5,1,[9,8,7,6],Y).
Y = [59876]

No comments:

Post a Comment