user997112
user997112

Reputation: 30615

lists adding elements (and splitting)

I'm adding a list and when I use MyArray|MyElement I print to screen and I get:

[obj1,obj2] | obj3

which isn't correct, is it? Ideally I want it to be:

[Obj1,Obj2,Obj3]

if I use MyArray|[MyElement]printing out gives me:

[Obj1,Obj2] | [Obj3]

is this the equivalent to [Obj1,Obj2,Obj3] ?

Upvotes: 2

Views: 144

Answers (3)

user1598696
user1598696

Reputation: 560

I don't know if I understand you question, but I'll try to help.

Try this if it works for you:

add2end(X,[],[X]).
add2end(X,[H|T],[H|NewT]):-add2end(X,T,NewT).

And for splitting:

split(L,N,L1,L2) :- the list L1 contains the first N elements of the list L, the list L2 contains the remaining elements. (list,integer,list,list) (?,+,?,?)

split(L,0,[],L).
split([X|Xs],N,[X|Ys],Zs) :- N > 0, N1 is N - 1, split(Xs,N1,Ys,Zs).

Upvotes: 0

Will Ness
Will Ness

Reputation: 71075

Using the syntax [ MyElement | MyArray ], you'd get

[Obj3, Obj1, Obj2]

This is what's known as "consing" an element onto a list. You could also use an append/3 predicate, like this:

append( MyArray, [MyElement], X).

which produces

X = [Obj1, Obj2, Obj3]

Upvotes: 2

user997112
user997112

Reputation: 30615

Figured it out, its because I was appending to the end of the list and the tail is always an array....

Upvotes: 1

Related Questions