0

I have a variable which has the following data structure, I want to replace all "foo" with all "goo" for the String part. Is there any one line neat code to do that? Want to see if any smart solutions to skip to write a loop. :)

var result = List[List[(List[String], Double)]]

regards, Lin

2 Answers 2

4

I am not sure if I got it right but maybe this is what you are looking for?

scala> val a: List[List[(List[String], Double)]] = List(List((List("foo asd", "asd foo"), 2.6)))
scala> a map (_ map { case (k, v) => (k map (_.replaceAll("foo", "goo")), v) })
res1: List[List[(List[String], Double)]] = List(List((List(goo asd, asd goo),2.6)))

Edit

to answer the comment let me first remove spaces and use dots

scala> a.map(_.map { case (k, v) => (k.map(_.replaceAll("foo", "goo")), v) })

and now, expand _.method(param) to x => x.method(param)

scala> a.map(b => b.map { case (k, v) => (k.map(c => c.replaceAll("foo", "goo")), v) })

You have 3 levels of nested lists, and one is inside a tuple, it won't be pretty, you need to map over each of them and extract last one from tuple.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Łukasz, vote up and what means _ in _ map?
See my edit, it is just a shorthand for more consise anonymous function
1
scala> val l = List(List((List("foo","afoo"),3.4),(List("gfoo","cfoo"),5.6)))
l: List[List[(List[String], Double)]] = List(List((List(foo, afoo),3.4), (List(gfoo, cfoo),5.6)))

scala> def replaceFoo(y:List[String]) = y.map(s => s.replace("foo","goo"))
replaceFoo: (y: List[String])List[String]

scala> l.map(x => x.map(y => (replaceFoo(y._1),y._2)))
res0: List[List[(List[String], Double)]] = List(List((List(goo, agoo),3.4), (List(ggoo, cgoo),5.6)))

3 Comments

Thanks Andrzej, always vote up before trying. :) Appreciate if you could elaborate a bit more for what this line means l.map(x => x.map(y => (y._1.map(s => s.replace("foo","goo")),y._2)))? Still seems a bit advanced to me. :)
Method replaceFoo - replace all foo to goo in list. This list is a first element of tuple (List[String],Double). About first element of tuple ask as _1, about second _2
Thanks Andrzej for the patience, mark your reply as answer. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.