1

I have a sentence (string) and a function that generates all synonyms of a given word from WordNet. I would like to produce a list of all possible variations of my sentence based on its synonyms.

Furthermore, I would like to maintain the order of the original sentence, meaning permutations should only contain synonyms of the first word as their first word, and permutations of the second word as their second word, etc.

For example, if my input is:

"5 centimeters"

My output should be along the lines of:

5 cm
5 centimetres
5 centi-meters
5 centi-metres
five cm
five centimetres
five centi-meters
five centi-metres

What is the best way to proceed with this in Scala? Thanks!

Michael
  • 343
  • 3
  • 13
  • 3
    Possible duplicate of [Cross product in Scala](https://stackoverflow.com/questions/14740199/cross-product-in-scala) – MeiSign Jan 23 '19 at 15:57
  • 1
    I think if you search in the context of cross product / carthesian product and scala you will find examples and solutions to this question. Post your code if you get stuck. This answer can be interesting for you in particular: https://stackoverflow.com/a/42095955/1995840 – MeiSign Jan 23 '19 at 15:59

1 Answers1

0

One answer to the question mentioned in the comments contains a useful crossJoin function that joins an arbitrary number of lists. This is my slightly edited version of it:

def crossJoin[T](list: Traversable[Traversable[T]]): Traversable[Traversable[T]] =
  list match {
    case Nil => Nil
    case x :: Nil => x map (Traversable(_))
    case x :: xs =>
      val xsJoin = crossJoin(xs)
      for {
        i <- x
        j <- xsJoin
      } yield {
        Traversable(i) ++ j
      }
  }

You also need some way of getting a list of synonyms for a word:

def synonyms(String): List[String]

Then your solution is just

val words: List[String] = "5 centimeters".split("\\s+").toList

crossJoin(words.map(synonyms))

That is, replace each word with a list of its synonyms and then cross join the result.

Tim
  • 26,753
  • 2
  • 16
  • 29