-2

I have, for example this number list:

[1,2,3,4,5,6,7,8,9,10].  

I have to search a number for example 7 and insert "$" BEFORE and AFTER 7:

[1,2,3,4,5,6,$,7,$,8,9,10].  

How can i do this?

Alessandro Minoccheri
  • 35,521
  • 22
  • 122
  • 171

1 Answers1

0

I use swi prolog, you could use a replace predicate (found in other stack overflow questions), combined with a flatten operator on a list:

:- use_module(library(lists)).

replace(_, _, [], []).
replace(O, R, [O|T], [R|T2]) :- replace(O, R, T, T2).
replace(O, R, [H|T], [H|T2]) :- H \= O, replace(O, R, T, T2).

now:

replace(1,[$,1,$],[4,3,2,1],NewList),flatten(NewList,FlattendList).
NewList = [4, 3, 2, [$, 1, $]],
FlattendList = [4, 3, 2, $, 1, $] ;

Of course you can build pretty predicate for that.

ri5b6
  • 370
  • 1
  • 10
  • Thanks for your reply i've understood, but now i've another little problem: If i have a list like this: [4, 3, 1, $, 1, $, $, 2, $, 4, $, $, 5, $] How can i delete duplicate: $$ In order to had this: [4, 3, 1, $, 1, $, 2, $, 4, $, 5, $] Thanks a lot :) – user1841520 Nov 21 '12 at 12:10
  • Last thing, how can i merge two part of the same list: [1,2,3,4,$,5,$,5,$,6,7] => [1,2,3,4,$,5,5,$,6,7]? Thanks. – user1841520 Nov 21 '12 at 12:22