function - Scala - Combine Substrings from a Vector using Reduce -
hi trying figure out way take first 2 letters of each name in vector , produce string of first 2 letters list combined.
val names: vector[string] = vector("june", "jane", "james", "iain", "kate", "beth", "george", "jack", "ben", "bob", "neil", "simon") val try1 = names.reduceleft((str1, str2) => str1.substring(0, 2) + str2.substring(0, 2)) val try2 = names.reduceleft((str1, str2) => str1 + str2.substring(0, 2)) //try1: string = jusi - both substringed //try2: string = junejajaiakabegejabebonesi str2 substring
the comments show respective results. presume results changing str1 stops iteration occuring (or atleast stops working intended). should here desired result? remove 'n' , 'e' final result, fact need suggests using wrong operation job.
you indeed cannot use reduce
do, since uses first element aggregator. use foldleft
:
names.foldleft("")((str1, str2) => str1 + str2.substring(0, 2))
to understand going on, let's @ simple example where:
val names = vector("june", "jane", "james")
using reduceleft
, get:
"june" + "jane".substring(0, 2) + "james".substring(0, 2)
using foldleft
, get:
"" + "june".substring(0, 2) + "james".substring(0, 2)
Comments
Post a Comment