Home > Software engineering >  Reducing/Folding a List of Strings to a Map[String,Boolean] in Scala
Reducing/Folding a List of Strings to a Map[String,Boolean] in Scala

Time:12-03

I have a list like this:

val objectKeys = List("Name","Place","Animal","Thing");

I want to reduce it to a Map[String,Boolean] where Boolean is element.size < 8.

Here's what I wrote:

val mappedObject = objectKeys.fold(Map[String,Boolean])((map,key) => map   (key -> key.size < 8))

which gives me the following error:

value   is not a member of Object, but could be made available as an extension method.

and

value size is not a member of Object

My understanding about fold is that it takes a default argument and reduces the entire value around it which however doesn't seem to work in this case. Can anyone help me with this?

Ideally mappedObject should be like:

val mappedObject = Map[String,Boolean]("Name"->true,"Place"->true,"Animal"->true,"Thing"->true)

An equivalent Javascript implementation will be:

const listValues = ["Name","Place","Animal","Thing"];
const reducedObject = listValues.reduce((acc,curr) => {acc[curr] = curr.length < 8;
             return acc;
},{});

CodePudding user response:

If you really want to do it with a fold, that's easy to do:

objectKeys.foldLeft(Map.empty[String, Boolean]) { (acc, key) =>
  acc   ((key, key.length < 8))
}

That said, I'm with Ivan on this one. map is clearly the better solution here (or fproduct if you're using the cats library).

CodePudding user response:

I think in this case you should just map to a tuple containing your key with boolean check and then convert it to Map[String, Boolean] via toMap method as following.

objectKeys.map(key => (key, key.length < 8)).toMap
  • Related