reset password
Author Message
Vanquish39
Posts: 134
Posted 02:47 Oct 16, 2012 |

Can someone please show me online, book, or video on how I can add a tuple to a list....  I've been stuck on this for an hour.

 

  var yy = List[(Char, Int)](('a', 2), ('b', 3), ('c', 1));

  var pair: (Char, Int) = ('c', 111)
 

how can i add pair to yy?  I've tried yy :+ pair and other functions none of which work.  Any idea? 

frodrig3
Posts: 2
Posted 03:22 Oct 16, 2012 |

I found something that works, but it doesn't look intuitive to me. I'm certain there's a better way to do it, but in the mean time:


 var yy = List[(Char, Int)] (('a', 2), ('b', 3), ('c', 1))
                                              
 var pair = List[(Char, Int)] (('c', 111))       
 
 val concatList : List[(Char, Int)] = yy ::: pair  


Hope this helps!

Vanquish39
Posts: 134
Posted 03:28 Oct 16, 2012 |

so how does one alter the count value in the tuple?  Lol

Delete and re-add?

Last edited by Vanquish39 at 03:29 Oct 16, 2012.
asmiths
Posts: 12
Posted 11:42 Oct 16, 2012 |

I have been using the operator "::" to concatenate lists and the objects that belong in them, for instance:

objectA :: List[Object] will return a List[Object] with the objectA at the head of the original List[Object]

This also works for list1 :: list2 as long as the lists contain the same objects/datatypes.

Correction: list1 :: list2 doesn't work.

 

So, in order to replace the Int in the List[(Char, Int)], we cannot just say Int = Int + 1.

What we do instead, is replace the list item with a new one of (Char, Int + 1).

If you wanted to change the object at the head of someList[(Char, Int)],  you would want to then concatenate:

(Char, Int + 1) :: someList.tail

Last edited by asmiths at 17:43 Oct 16, 2012.
rabbott
Posts: 1649
Posted 20:18 Oct 16, 2012 |

What ASMITHS said is correct.

The :: operator adds an element to the front of a list. So to use the original example,

val newList1 List([Char, Int)] = pair :: yy

creates list called newList1, whose head is pair and whose tail is yy, i.e., the list List( (c,111), (a,2), (b,3), (c,1))

The operator :+ adds an element to the end of a list.

  val newList2 = yy :+ pair            

creates: List((a,2), (b,3), (c,1), (c,111))

Finally, the operator  :::  concatenates two lists. 

val newList3 = newList1 ::: newList2

creates  List( (c,111), (a,2), (b,3), (c,1), (a,2), (b,3), (c,1), (c,111))

 
Last edited by rabbott at 20:19 Oct 16, 2012.