Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Scala fold function to detect occurrence of a value in Seq[String]

I’m trying to write a scala function to detect whether a site id (site_id) exists within a sequence of targeted site ids (targetedSiteIds).

If the site id exists in the Seq, the function filterSiteById returns true, else it returns false.

However, the code below keeps giving me the error error: Targeting does not take type parameters.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could you help me fix this issue?

Thanks in advance!


val site_id = "0011a522ce0f4bbbbaa6b3c38cafaa0f"

targeting = Targeting(targetedSiteIds=Seq("0009a522ce0f4bbbbaa6b3c38cafaa0f","0010a522ce0f4bbbbaa6b3c38cafaa0f","0011a522ce0f4bbbbaa6b3c38cafaa0f") // TargetedSiteIds)

case class Targeting(targetedSiteIds: Seq[String])

var trueOrFalse=filterSitesById(targeting) // true or false

def filterSitesById(sites: Targeting[Seq[String]]): Boolean = {
  sites.fold(false)(_.exists(_.idx==site_id))
}

>Solution :

case class Targeting(targetedSiteIds: Seq[String])

val site_id = "0011a522ce0f4bbbbaa6b3c38cafaa0f"

val targeting = Targeting(targetedSiteIds = Seq("0009a522ce0f4bbbbaa6b3c38cafaa0f","0010a522ce0f4bbbbaa6b3c38cafaa0f","0011a522ce0f4bbbbaa6b3c38cafaa0f"))

def filterSitesById(sites: Targeting): Boolean = {
  sites.targetedSiteIds.exists(_ == site_id)
}

filterSitesById(targeting)
  1. signature should be either def filterSitesById(sites: Targeting or filterSitesById(sites: Seq[String]]), indeed there is no Targeting[Seq[String]] type
  2. code inside the function was wrong as well – if it’s fold, then it would only combine results into the same type (Seq[String] cannot be folded into Boolean), if it’s foldLeft then the lambda should combine Boolean result with String, if it uses exists… any manual folding is unnecessary
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading