scala append to to list of tuples in foldLeft? -
i'm beginner in scala, , i'm wondering how append, or create new list of tuples tuple @ head of tuple.
right doing
list.foldleft(list[(string, int)]())((ll:list[(string, int)], str:string) => if (str == ll.head._1) (str, ll.head._2 + 1) :: ll.tail.head else (str, 1) :: ll.head)
however error there no :: operator tuples.
if understand you're trying do, reason you're trying use first element of tail of list rather tail right-hand argument ::
.
you should able use like:
list.foldleft(list[(string, int)]())((ll, str) => if (str == ll.head._1) (str, ll.head._2 + 1) :: ll.tail else (str, 1) :: ll)
however you'll hit error trying take head of empty list. full working version like
list.foldleft(list[(string, int)]()) { case ((hs, hc) :: tail, str) if hs == str ⇒ (str, hc + 1) :: tail case (ll, str) ⇒ (str, 1) :: ll }
Comments
Post a Comment